欢欲药 v1.1.4版本的 MD5 值为:7d0994a905ec6c6aceeef0cd822647fc

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


package im.czepdgxadm.messenger;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.SparseArray;
import androidx.exifinterface.media.ExifInterface;
import com.google.android.exoplayer2.util.MimeTypes;
import com.king.zxing.util.LogUtils;
import im.czepdgxadm.messenger.FileLoader;
import im.czepdgxadm.messenger.ImageLoader;
import im.czepdgxadm.messenger.secretmedia.EncryptedFileInputStream;
import im.czepdgxadm.tgnet.ConnectionsManager;
import im.czepdgxadm.tgnet.RequestDelegate;
import im.czepdgxadm.tgnet.TLObject;
import im.czepdgxadm.tgnet.TLRPC;
import im.czepdgxadm.ui.components.AnimatedFileDrawable;
import im.czepdgxadm.ui.components.RLottieDrawable;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import kotlin.UByte;
import org.json.JSONArray;
import org.json.JSONObject;

public class ImageLoader {
    public static final String AUTOPLAY_FILTER = "g";
    private boolean canForce8888;
    private LruCache<RLottieDrawable> lottieMemCache;
    private LruCache<BitmapDrawable> memCache;
    private static ThreadLocal<byte[]> bytesLocal = new ThreadLocal<>();
    private static ThreadLocal<byte[]> bytesThumbLocal = new ThreadLocal<>();
    private static byte[] header = new byte[12];
    private static byte[] headerThumb = new byte[12];
    private static volatile ImageLoader Instance = null;
    private HashMap<String, Integer> bitmapUseCounts = new HashMap<>();
    private HashMap<String, CacheImage> imageLoadingByUrl = new HashMap<>();
    private HashMap<String, CacheImage> imageLoadingByKeys = new HashMap<>();
    private SparseArray<CacheImage> imageLoadingByTag = new SparseArray<>();
    private HashMap<String, ThumbGenerateInfo> waitingForQualityThumb = new HashMap<>();
    private SparseArray<String> waitingForQualityThumbByTag = new SparseArray<>();
    private LinkedList<HttpImageTask> httpTasks = new LinkedList<>();
    private LinkedList<ArtworkLoadTask> artworkTasks = new LinkedList<>();
    private DispatchQueue cacheOutQueue = new DispatchQueue("cacheOutQueue");
    private DispatchQueue cacheThumbOutQueue = new DispatchQueue("cacheThumbOutQueue");
    private DispatchQueue thumbGeneratingQueue = new DispatchQueue("thumbGeneratingQueue");
    private DispatchQueue imageLoadQueue = new DispatchQueue("imageLoadQueue");
    private HashMap<String, String> replacedBitmaps = new HashMap<>();
    private ConcurrentHashMap<String, Float> fileProgresses = new ConcurrentHashMap<>();
    private HashMap<String, ThumbGenerateTask> thumbGenerateTasks = new HashMap<>();
    private HashMap<String, Integer> forceLoadingImages = new HashMap<>();
    private int currentHttpTasksCount = 0;
    private int currentArtworkTasksCount = 0;
    private ConcurrentHashMap<String, WebFile> testWebFile = new ConcurrentHashMap<>();
    private LinkedList<HttpFileTask> httpFileLoadTasks = new LinkedList<>();
    private HashMap<String, HttpFileTask> httpFileLoadTasksByKeys = new HashMap<>();
    private HashMap<String, Runnable> retryHttpsTasks = new HashMap<>();
    private int currentHttpFileLoadTasksCount = 0;
    private String ignoreRemoval = null;
    private volatile long lastCacheOutTime = 0;
    private int lastImageNum = 0;
    private long lastProgressUpdateTime = 0;
    private File appPath = null;

    public class ThumbGenerateInfo {
        private boolean big;
        private String filter;
        private ArrayList<ImageReceiver> imageReceiverArray;
        private ArrayList<Integer> imageReceiverGuidsArray;
        private TLRPC.Document parentDocument;

        private ThumbGenerateInfo() {
            this.imageReceiverArray = new ArrayList<>();
            this.imageReceiverGuidsArray = new ArrayList<>();
        }
    }

    public class HttpFileTask extends AsyncTask<Void, Void, Boolean> {
        private int currentAccount;
        private String ext;
        private int fileSize;
        private long lastProgressTime;
        private File tempFile;
        private String url;
        private RandomAccessFile fileOutputStream = null;
        private boolean canRetry = true;

        public HttpFileTask(String url, File tempFile, String ext, int currentAccount) {
            this.url = url;
            this.tempFile = tempFile;
            this.ext = ext;
            this.currentAccount = currentAccount;
        }

        private void reportProgress(final float progress) {
            long currentTime = System.currentTimeMillis();
            if (progress != 1.0f) {
                long j = this.lastProgressTime;
                if (j != 0 && j >= currentTime - 500) {
                    return;
                }
            }
            this.lastProgressTime = currentTime;
            Utilities.stageQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpFileTask.this.m263x8542461f(progress);
                }
            });
        }

        public void m263x8542461f(final float progress) {
            ImageLoader.this.fileProgresses.put(this.url, Float.valueOf(progress));
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpFileTask.this.m262x9398a000(progress);
                }
            });
        }

        public void m262x9398a000(float progress) {
            NotificationCenter.getInstance(this.currentAccount).postNotificationName(NotificationCenter.FileLoadProgressChanged, this.url, Float.valueOf(progress));
        }

        @Override
        public Boolean doInBackground(Void... voids) {
            List values;
            String length;
            int code;
            InputStream httpConnectionStream = null;
            boolean done = false;
            URLConnection httpConnection = null;
            try {
                URL downloadUrl = new URL(this.url);
                httpConnection = downloadUrl.openConnection();
                httpConnection.addRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A5297c Safari/602.1");
                httpConnection.setConnectTimeout(5000);
                httpConnection.setReadTimeout(5000);
                if (httpConnection instanceof HttpURLConnection) {
                    HttpURLConnection httpURLConnection = (HttpURLConnection) httpConnection;
                    httpURLConnection.setInstanceFollowRedirects(true);
                    int status = httpURLConnection.getResponseCode();
                    if (status == 302 || status == 301 || status == 303) {
                        String newUrl = httpURLConnection.getHeaderField("Location");
                        String cookies = httpURLConnection.getHeaderField("Set-Cookie");
                        URL downloadUrl2 = new URL(newUrl);
                        httpConnection = downloadUrl2.openConnection();
                        httpConnection.setRequestProperty("Cookie", cookies);
                        httpConnection.addRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A5297c Safari/602.1");
                    }
                }
                httpConnection.connect();
                httpConnectionStream = httpConnection.getInputStream();
                this.fileOutputStream = new RandomAccessFile(this.tempFile, "rws");
            } catch (Throwable e) {
                if (e instanceof SocketTimeoutException) {
                    if (ApplicationLoader.isNetworkOnline()) {
                        this.canRetry = false;
                    }
                } else if (e instanceof UnknownHostException) {
                    this.canRetry = false;
                } else if (e instanceof SocketException) {
                    if (e.getMessage() != null && e.getMessage().contains("ECONNRESET")) {
                        this.canRetry = false;
                    }
                } else if (e instanceof FileNotFoundException) {
                    this.canRetry = false;
                }
                FileLog.e(e);
            }
            if (this.canRetry) {
                try {
                    if ((httpConnection instanceof HttpURLConnection) && (code = ((HttpURLConnection) httpConnection).getResponseCode()) != 200 && code != 202 && code != 304) {
                        this.canRetry = false;
                    }
                } catch (Exception e2) {
                    FileLog.e(e2);
                }
                if (httpConnection != null) {
                    try {
                        Map<String, List<String>> headerFields = httpConnection.getHeaderFields();
                        if (headerFields != null && (values = headerFields.get("content-Length")) != null && !values.isEmpty() && (length = values.get(0)) != null) {
                            this.fileSize = Utilities.parseInt(length).intValue();
                        }
                    } catch (Exception e3) {
                        FileLog.e(e3);
                    }
                }
                if (httpConnectionStream != null) {
                    try {
                        byte[] data = new byte[32768];
                        int totalLoaded = 0;
                        while (!isCancelled()) {
                            try {
                                int read = httpConnectionStream.read(data);
                                if (read > 0) {
                                    this.fileOutputStream.write(data, 0, read);
                                    totalLoaded += read;
                                    int i = this.fileSize;
                                    if (i > 0) {
                                        reportProgress(totalLoaded / i);
                                    }
                                } else if (read == -1) {
                                    done = true;
                                    if (this.fileSize != 0) {
                                        reportProgress(1.0f);
                                    }
                                }
                            } catch (Exception e4) {
                                FileLog.e(e4);
                            }
                        }
                    } catch (Throwable e5) {
                        FileLog.e(e5);
                    }
                }
                try {
                    RandomAccessFile randomAccessFile = this.fileOutputStream;
                    if (randomAccessFile != null) {
                        randomAccessFile.close();
                        this.fileOutputStream = null;
                    }
                } catch (Throwable e6) {
                    FileLog.e(e6);
                }
                if (httpConnectionStream != null) {
                    try {
                        httpConnectionStream.close();
                    } catch (Throwable e7) {
                        FileLog.e(e7);
                    }
                }
            }
            return Boolean.valueOf(done);
        }

        @Override
        public void onPostExecute(Boolean result) {
            ImageLoader.this.runHttpFileLoadTasks(this, result.booleanValue() ? 2 : 1);
        }

        @Override
        protected void onCancelled() {
            ImageLoader.this.runHttpFileLoadTasks(this, 2);
        }
    }

    public class ArtworkLoadTask extends AsyncTask<Void, Void, String> {
        private CacheImage cacheImage;
        private boolean canRetry = true;
        private HttpURLConnection httpConnection;
        private boolean small;

        public ArtworkLoadTask(CacheImage cacheImage) {
            this.cacheImage = cacheImage;
            Uri uri = Uri.parse(cacheImage.imageLocation.path);
            this.small = uri.getQueryParameter("s") != null;
        }

        @Override
        public String doInBackground(Void... voids) {
            int read;
            int code;
            ByteArrayOutputStream outbuf = null;
            InputStream httpConnectionStream = null;
            try {
                try {
                    String location = this.cacheImage.imageLocation.path;
                    URL downloadUrl = new URL(location.replace("athumb://", "https://"));
                    HttpURLConnection httpURLConnection = (HttpURLConnection) downloadUrl.openConnection();
                    this.httpConnection = httpURLConnection;
                    httpURLConnection.addRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A5297c Safari/602.1");
                    this.httpConnection.setConnectTimeout(5000);
                    this.httpConnection.setReadTimeout(5000);
                    this.httpConnection.connect();
                    try {
                        HttpURLConnection httpURLConnection2 = this.httpConnection;
                        if (httpURLConnection2 != null && (code = httpURLConnection2.getResponseCode()) != 200 && code != 202 && code != 304) {
                            this.canRetry = false;
                        }
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                    httpConnectionStream = this.httpConnection.getInputStream();
                    outbuf = new ByteArrayOutputStream();
                    byte[] data = new byte[32768];
                    while (!isCancelled() && (read = httpConnectionStream.read(data)) > 0) {
                        outbuf.write(data, 0, read);
                    }
                    this.canRetry = false;
                    JSONObject object = new JSONObject(new String(outbuf.toByteArray()));
                    JSONArray array = object.getJSONArray("results");
                    if (array.length() <= 0) {
                        try {
                            HttpURLConnection httpURLConnection3 = this.httpConnection;
                            if (httpURLConnection3 != null) {
                                httpURLConnection3.disconnect();
                            }
                        } catch (Throwable th) {
                        }
                        if (httpConnectionStream != null) {
                            try {
                                httpConnectionStream.close();
                            } catch (Throwable e2) {
                                FileLog.e(e2);
                            }
                        }
                        outbuf.close();
                        return null;
                    }
                    JSONObject media = array.getJSONObject(0);
                    String artworkUrl100 = media.getString("artworkUrl100");
                    if (this.small) {
                        try {
                            HttpURLConnection httpURLConnection4 = this.httpConnection;
                            if (httpURLConnection4 != null) {
                                httpURLConnection4.disconnect();
                            }
                        } catch (Throwable th2) {
                        }
                        if (httpConnectionStream != null) {
                            try {
                                httpConnectionStream.close();
                            } catch (Throwable e3) {
                                FileLog.e(e3);
                            }
                        }
                        try {
                            outbuf.close();
                        } catch (Exception e4) {
                        }
                        return artworkUrl100;
                    }
                    String replace = artworkUrl100.replace("100x100", "600x600");
                    try {
                        HttpURLConnection httpURLConnection5 = this.httpConnection;
                        if (httpURLConnection5 != null) {
                            httpURLConnection5.disconnect();
                        }
                    } catch (Throwable th3) {
                    }
                    if (httpConnectionStream != null) {
                        try {
                            httpConnectionStream.close();
                        } catch (Throwable e5) {
                            FileLog.e(e5);
                        }
                    }
                    try {
                        outbuf.close();
                    } catch (Exception e6) {
                    }
                    return replace;
                } catch (Exception e7) {
                    return null;
                }
            } catch (Throwable e8) {
                try {
                    if (e8 instanceof SocketTimeoutException) {
                        if (ApplicationLoader.isNetworkOnline()) {
                            this.canRetry = false;
                        }
                    } else if (e8 instanceof UnknownHostException) {
                        this.canRetry = false;
                    } else if (e8 instanceof SocketException) {
                        if (e8.getMessage() != null && e8.getMessage().contains("ECONNRESET")) {
                            this.canRetry = false;
                        }
                    } else if (e8 instanceof FileNotFoundException) {
                        this.canRetry = false;
                    }
                    FileLog.e(e8);
                    try {
                        HttpURLConnection httpURLConnection6 = this.httpConnection;
                        if (httpURLConnection6 != null) {
                            httpURLConnection6.disconnect();
                        }
                    } catch (Throwable th4) {
                    }
                    if (httpConnectionStream != null) {
                        try {
                            httpConnectionStream.close();
                        } catch (Throwable e9) {
                            FileLog.e(e9);
                        }
                    }
                    if (outbuf == null) {
                        return null;
                    }
                    outbuf.close();
                    return null;
                } catch (Throwable th5) {
                    try {
                        HttpURLConnection httpURLConnection7 = this.httpConnection;
                        if (httpURLConnection7 != null) {
                            httpURLConnection7.disconnect();
                        }
                    } catch (Throwable th6) {
                    }
                    if (httpConnectionStream != null) {
                        try {
                            httpConnectionStream.close();
                        } catch (Throwable e10) {
                            FileLog.e(e10);
                        }
                    }
                    if (outbuf == null) {
                        throw th5;
                    }
                    try {
                        outbuf.close();
                        throw th5;
                    } catch (Exception e11) {
                        throw th5;
                    }
                }
            }
        }

        @Override
        public void onPostExecute(String result) {
            if (result != null) {
                this.cacheImage.httpTask = new HttpImageTask(this.cacheImage, 0, result);
                ImageLoader.this.httpTasks.add(this.cacheImage.httpTask);
                ImageLoader.this.runHttpTasks(false);
            } else if (this.canRetry) {
                ImageLoader.this.artworkLoadError(this.cacheImage.url);
            }
            ImageLoader.this.imageLoadQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.ArtworkLoadTask.this.m258x6ef55303();
                }
            });
        }

        public void m258x6ef55303() {
            ImageLoader.this.runArtworkTasks(true);
        }

        public void m257x5f58af20() {
            ImageLoader.this.runArtworkTasks(true);
        }

        @Override
        protected void onCancelled() {
            ImageLoader.this.imageLoadQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.ArtworkLoadTask.this.m257x5f58af20();
                }
            });
        }
    }

    public class HttpImageTask extends AsyncTask<Void, Void, Boolean> {
        private CacheImage cacheImage;
        private boolean canRetry = true;
        private RandomAccessFile fileOutputStream;
        private HttpURLConnection httpConnection;
        private int imageSize;
        private long lastProgressTime;
        private String overrideUrl;

        public HttpImageTask(CacheImage cacheImage, int size) {
            this.cacheImage = cacheImage;
            this.imageSize = size;
        }

        public HttpImageTask(CacheImage cacheImage, int size, String url) {
            this.cacheImage = cacheImage;
            this.imageSize = size;
            this.overrideUrl = url;
        }

        private void reportProgress(final float progress) {
            long currentTime = System.currentTimeMillis();
            if (progress != 1.0f) {
                long j = this.lastProgressTime;
                if (j != 0 && j >= currentTime - 500) {
                    return;
                }
            }
            this.lastProgressTime = currentTime;
            Utilities.stageQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.m271x3dc70842(progress);
                }
            });
        }

        public void m271x3dc70842(final float progress) {
            ImageLoader.this.fileProgresses.put(this.cacheImage.url, Float.valueOf(progress));
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.m270xfa3bea81(progress);
                }
            });
        }

        public void m270xfa3bea81(float progress) {
            NotificationCenter.getInstance(this.cacheImage.currentAccount).postNotificationName(NotificationCenter.FileLoadProgressChanged, this.cacheImage.url, Float.valueOf(progress));
        }

        @Override
        public Boolean doInBackground(Void... voids) {
            int provider;
            WebFile webFile;
            HttpURLConnection httpURLConnection;
            List values;
            String length;
            int code;
            InputStream httpConnectionStream = null;
            boolean done = false;
            if (!isCancelled()) {
                try {
                    String location = this.cacheImage.imageLocation.path;
                    if ((location.startsWith("https://static-maps") || location.startsWith("https://maps.googleapis")) && (((provider = MessagesController.getInstance(this.cacheImage.currentAccount).mapProvider) == 3 || provider == 4) && (webFile = (WebFile) ImageLoader.this.testWebFile.get(location)) != null)) {
                        TLRPC.TL_upload_getWebFile req = new TLRPC.TL_upload_getWebFile();
                        req.location = webFile.location;
                        req.offset = 0;
                        req.limit = 0;
                        ConnectionsManager.getInstance(this.cacheImage.currentAccount).sendRequest(req, new RequestDelegate() {
                            @Override
                            public final void run(TLObject tLObject, TLRPC.TL_error tL_error) {
                                ImageLoader.HttpImageTask.lambda$doInBackground$2(tLObject, tL_error);
                            }
                        });
                    }
                    String str = this.overrideUrl;
                    if (str == null) {
                        str = location;
                    }
                    URL downloadUrl = new URL(str);
                    HttpURLConnection httpURLConnection2 = (HttpURLConnection) downloadUrl.openConnection();
                    this.httpConnection = httpURLConnection2;
                    httpURLConnection2.addRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A5297c Safari/602.1");
                    this.httpConnection.setConnectTimeout(5000);
                    this.httpConnection.setReadTimeout(5000);
                    this.httpConnection.setInstanceFollowRedirects(true);
                    if (!isCancelled()) {
                        this.httpConnection.connect();
                        httpConnectionStream = this.httpConnection.getInputStream();
                        this.fileOutputStream = new RandomAccessFile(this.cacheImage.tempFilePath, "rws");
                    }
                } catch (Throwable e) {
                    if (e instanceof SocketTimeoutException) {
                        if (ApplicationLoader.isNetworkOnline()) {
                            this.canRetry = false;
                        }
                    } else if (e instanceof UnknownHostException) {
                        this.canRetry = false;
                    } else if (e instanceof SocketException) {
                        if (e.getMessage() != null && e.getMessage().contains("ECONNRESET")) {
                            this.canRetry = false;
                        }
                    } else if (e instanceof FileNotFoundException) {
                        this.canRetry = false;
                    }
                    FileLog.e(e);
                }
            }
            if (!isCancelled()) {
                try {
                    HttpURLConnection httpURLConnection3 = this.httpConnection;
                    if (httpURLConnection3 != null && (code = httpURLConnection3.getResponseCode()) != 200 && code != 202 && code != 304) {
                        this.canRetry = false;
                    }
                } catch (Exception e2) {
                    FileLog.e(e2);
                }
                if (this.imageSize == 0 && (httpURLConnection = this.httpConnection) != null) {
                    try {
                        Map<String, List<String>> headerFields = httpURLConnection.getHeaderFields();
                        if (headerFields != null && (values = headerFields.get("content-Length")) != null && !values.isEmpty() && (length = values.get(0)) != null) {
                            this.imageSize = Utilities.parseInt(length).intValue();
                        }
                    } catch (Exception e3) {
                        FileLog.e(e3);
                    }
                }
                if (httpConnectionStream != null) {
                    try {
                        byte[] data = new byte[8192];
                        int totalLoaded = 0;
                        while (!isCancelled()) {
                            try {
                                int read = httpConnectionStream.read(data);
                                if (read > 0) {
                                    totalLoaded += read;
                                    this.fileOutputStream.write(data, 0, read);
                                    int i = this.imageSize;
                                    if (i != 0) {
                                        reportProgress(totalLoaded / i);
                                    }
                                } else if (read == -1) {
                                    done = true;
                                    if (this.imageSize != 0) {
                                        reportProgress(1.0f);
                                    }
                                }
                            } catch (Exception e4) {
                                FileLog.e(e4);
                            }
                        }
                    } catch (Throwable e5) {
                        FileLog.e(e5);
                    }
                }
            }
            try {
                RandomAccessFile randomAccessFile = this.fileOutputStream;
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                    this.fileOutputStream = null;
                }
            } catch (Throwable e6) {
                FileLog.e(e6);
            }
            try {
                HttpURLConnection httpURLConnection4 = this.httpConnection;
                if (httpURLConnection4 != null) {
                    httpURLConnection4.disconnect();
                }
            } catch (Throwable th) {
            }
            if (httpConnectionStream != null) {
                try {
                    httpConnectionStream.close();
                } catch (Throwable e7) {
                    FileLog.e(e7);
                }
            }
            if (done && this.cacheImage.tempFilePath != null && !this.cacheImage.tempFilePath.renameTo(this.cacheImage.finalFilePath)) {
                CacheImage cacheImage = this.cacheImage;
                cacheImage.finalFilePath = cacheImage.tempFilePath;
            }
            return Boolean.valueOf(done);
        }

        public static void lambda$doInBackground$2(TLObject response, TLRPC.TL_error error) {
        }

        @Override
        public void onPostExecute(final Boolean result) {
            if (result.booleanValue() || !this.canRetry) {
                ImageLoader.this.fileDidLoaded(this.cacheImage.url, this.cacheImage.finalFilePath, 0);
            } else {
                ImageLoader.this.httpFileLoadError(this.cacheImage.url);
            }
            Utilities.stageQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.m268xf65a9d40(result);
                }
            });
            ImageLoader.this.imageLoadQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.m269x39e5bb01();
                }
            });
        }

        public void m268xf65a9d40(final Boolean result) {
            ImageLoader.this.fileProgresses.remove(this.cacheImage.url);
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.m267xb2cf7f7f(result);
                }
            });
        }

        public void m267xb2cf7f7f(Boolean result) {
            if (result.booleanValue()) {
                NotificationCenter.getInstance(this.cacheImage.currentAccount).postNotificationName(NotificationCenter.fileDidLoad, this.cacheImage.url, this.cacheImage.finalFilePath);
            } else {
                NotificationCenter.getInstance(this.cacheImage.currentAccount).postNotificationName(NotificationCenter.fileDidFailToLoad, this.cacheImage.url, 2);
            }
        }

        public void m269x39e5bb01() {
            ImageLoader.this.runHttpTasks(true);
        }

        public void m264x88bb7a5e() {
            ImageLoader.this.runHttpTasks(true);
        }

        @Override
        protected void onCancelled() {
            ImageLoader.this.imageLoadQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.m264x88bb7a5e();
                }
            });
            Utilities.stageQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.m266xfd1b5e0();
                }
            });
        }

        public void m266xfd1b5e0() {
            ImageLoader.this.fileProgresses.remove(this.cacheImage.url);
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.m265xcc46981f();
                }
            });
        }

        public void m265xcc46981f() {
            NotificationCenter.getInstance(this.cacheImage.currentAccount).postNotificationName(NotificationCenter.fileDidFailToLoad, this.cacheImage.url, 1);
        }
    }

    public class ThumbGenerateTask implements Runnable {
        private ThumbGenerateInfo info;
        private int mediaType;
        private File originalPath;

        public ThumbGenerateTask(int type, File path, ThumbGenerateInfo i) {
            this.mediaType = type;
            this.originalPath = path;
            this.info = i;
        }

        private void removeTask() {
            ThumbGenerateInfo thumbGenerateInfo = this.info;
            if (thumbGenerateInfo != null) {
                final String name = FileLoader.getAttachFileName(thumbGenerateInfo.parentDocument);
                ImageLoader.this.imageLoadQueue.postRunnable(new Runnable() {
                    @Override
                    public final void run() {
                        ImageLoader.ThumbGenerateTask.this.m272x5ba6e8e1(name);
                    }
                });
            }
        }

        public void m272x5ba6e8e1(String name) {
            ImageLoader.this.thumbGenerateTasks.remove(name);
        }

        @Override
        public void run() {
            Bitmap originalBitmap;
            Bitmap scaledBitmap;
            try {
                if (this.info != null) {
                    final String key = "q_" + this.info.parentDocument.dc_id + "_" + this.info.parentDocument.id;
                    File thumbFile = new File(FileLoader.getDirectory(4), key + ".jpg");
                    if (!thumbFile.exists() && this.originalPath.exists()) {
                        int size = this.info.big ? Math.max(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) : Math.min(180, Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) / 4);
                        Bitmap originalBitmap2 = null;
                        int i = this.mediaType;
                        if (i == 0) {
                            originalBitmap2 = ImageLoader.loadBitmap(this.originalPath.toString(), null, size, size, false);
                        } else {
                            int i2 = 2;
                            if (i == 2) {
                                String file = this.originalPath.toString();
                                if (!this.info.big) {
                                    i2 = 1;
                                }
                                originalBitmap2 = ThumbnailUtils.createVideoThumbnail(file, i2);
                            } else if (i == 3) {
                                String path = this.originalPath.toString().toLowerCase();
                                if (path.endsWith("mp4")) {
                                    String file2 = this.originalPath.toString();
                                    if (!this.info.big) {
                                        i2 = 1;
                                    }
                                    originalBitmap2 = ThumbnailUtils.createVideoThumbnail(file2, i2);
                                } else if (path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".png") || path.endsWith(".gif")) {
                                    originalBitmap2 = ImageLoader.loadBitmap(path, null, size, size, false);
                                }
                            }
                        }
                        if (originalBitmap2 == null) {
                            removeTask();
                            return;
                        }
                        int w = originalBitmap2.getWidth();
                        int h = originalBitmap2.getHeight();
                        if (w != 0 && h != 0) {
                            float scaleFactor = Math.min(w / size, h / size);
                            if (scaleFactor > 1.0f && (scaledBitmap = Bitmaps.createScaledBitmap(originalBitmap2, (int) (w / scaleFactor), (int) (h / scaleFactor), true)) != originalBitmap2) {
                                originalBitmap2.recycle();
                                originalBitmap = scaledBitmap;
                            } else {
                                originalBitmap = originalBitmap2;
                            }
                            FileOutputStream stream = new FileOutputStream(thumbFile);
                            originalBitmap.compress(Bitmap.CompressFormat.JPEG, this.info.big ? 83 : 60, stream);
                            try {
                                stream.close();
                            } catch (Exception e) {
                                FileLog.e(e);
                            }
                            final BitmapDrawable bitmapDrawable = new BitmapDrawable(originalBitmap);
                            final ArrayList<ImageReceiver> finalImageReceiverArray = new ArrayList<>(this.info.imageReceiverArray);
                            final ArrayList<Integer> finalImageReceiverGuidsArray = new ArrayList<>(this.info.imageReceiverGuidsArray);
                            AndroidUtilities.runOnUIThread(new Runnable() {
                                @Override
                                public final void run() {
                                    ImageLoader.ThumbGenerateTask.this.m273x5abc792a(key, finalImageReceiverArray, bitmapDrawable, finalImageReceiverGuidsArray);
                                }
                            });
                            return;
                        }
                        removeTask();
                        return;
                    }
                    removeTask();
                    return;
                }
                removeTask();
            } catch (Throwable e2) {
                FileLog.e(e2);
                removeTask();
            }
        }

        public void m273x5abc792a(String key, ArrayList finalImageReceiverArray, BitmapDrawable bitmapDrawable, ArrayList finalImageReceiverGuidsArray) {
            removeTask();
            String kf = key;
            if (this.info.filter != null) {
                kf = kf + "@" + this.info.filter;
            }
            for (int a = 0; a < finalImageReceiverArray.size(); a++) {
                ImageReceiver imgView = (ImageReceiver) finalImageReceiverArray.get(a);
                imgView.setImageBitmapByKey(bitmapDrawable, kf, 0, false, ((Integer) finalImageReceiverGuidsArray.get(a)).intValue());
            }
            ImageLoader.this.memCache.put(kf, bitmapDrawable);
        }
    }

    public class CacheOutTask implements Runnable {
        private CacheImage cacheImage;
        private boolean isCancelled;
        private Thread runningThread;
        private final Object sync = new Object();

        public CacheOutTask(CacheImage image) {
            this.cacheImage = image;
        }

        @Override
        public void run() {
            Bitmap bitmap;
            File file;
            SecureDocumentKey secureDocumentKey;
            byte[] bArr;
            Long l;
            BitmapFactory.Options options;
            float f;
            boolean z;
            boolean z2;
            Bitmap bitmap2;
            int i;
            float f2;
            int i2;
            float f3;
            boolean z3;
            int i3;
            float f4;
            boolean z4;
            byte[] bArr2;
            boolean z5;
            Bitmap createScaledBitmap;
            FileInputStream fileInputStream;
            Bitmap bitmap3;
            int i4;
            char c;
            AnimatedFileDrawable animatedFileDrawable;
            synchronized (this.sync) {
                this.runningThread = Thread.currentThread();
                Thread.interrupted();
                if (this.isCancelled) {
                    return;
                }
                if (this.cacheImage.imageLocation.photoSize instanceof TLRPC.TL_photoStrippedSize) {
                    synchronized (this.sync) {
                        if (this.isCancelled) {
                            return;
                        }
                        TLRPC.TL_photoStrippedSize tL_photoStrippedSize = (TLRPC.TL_photoStrippedSize) this.cacheImage.imageLocation.photoSize;
                        int length = (tL_photoStrippedSize.bytes.length - 3) + Bitmaps.header.length + Bitmaps.footer.length;
                        byte[] bArr3 = (byte[]) ImageLoader.bytesLocal.get();
                        byte[] bArr4 = (bArr3 == null || bArr3.length < length) ? null : bArr3;
                        if (bArr4 == null) {
                            byte[] bArr5 = new byte[length];
                            bArr4 = bArr5;
                            ImageLoader.bytesLocal.set(bArr5);
                        }
                        System.arraycopy(Bitmaps.header, 0, bArr4, 0, Bitmaps.header.length);
                        System.arraycopy(tL_photoStrippedSize.bytes, 3, bArr4, Bitmaps.header.length, tL_photoStrippedSize.bytes.length - 3);
                        System.arraycopy(Bitmaps.footer, 0, bArr4, (Bitmaps.header.length + tL_photoStrippedSize.bytes.length) - 3, Bitmaps.footer.length);
                        bArr4[164] = tL_photoStrippedSize.bytes[1];
                        bArr4[166] = tL_photoStrippedSize.bytes[2];
                        Bitmap decodeByteArray = BitmapFactory.decodeByteArray(bArr4, 0, length);
                        if (decodeByteArray != null && !TextUtils.isEmpty(this.cacheImage.filter) && this.cacheImage.filter.contains("b")) {
                            Utilities.blurBitmap(decodeByteArray, 3, 1, decodeByteArray.getWidth(), decodeByteArray.getHeight(), decodeByteArray.getRowBytes());
                        }
                        onPostExecute(decodeByteArray != null ? new BitmapDrawable(decodeByteArray) : null);
                        return;
                    }
                }
                if (this.cacheImage.lottieFile) {
                    synchronized (this.sync) {
                        if (this.isCancelled) {
                            return;
                        }
                        int min = Math.min(512, AndroidUtilities.dp(170.6f));
                        int min2 = Math.min(512, AndroidUtilities.dp(170.6f));
                        boolean z6 = false;
                        boolean z7 = false;
                        int i5 = 1;
                        int[] iArr = null;
                        if (this.cacheImage.filter != null) {
                            String[] split = this.cacheImage.filter.split("_");
                            if (split.length >= 2) {
                                float parseFloat = Float.parseFloat(split[0]);
                                float parseFloat2 = Float.parseFloat(split[1]);
                                min = Math.min(512, (int) (parseFloat * AndroidUtilities.density));
                                min2 = Math.min(512, (int) (AndroidUtilities.density * parseFloat2));
                                if (parseFloat <= 90.0f && parseFloat2 <= 90.0f) {
                                    min = Math.min(min, 160);
                                    min2 = Math.min(min2, 160);
                                    z7 = true;
                                    z6 = SharedConfig.getDevicePerfomanceClass() != 2;
                                }
                            }
                            if (split.length >= 3) {
                                if ("nr".equals(split[2])) {
                                    i5 = 2;
                                } else if ("nrs".equals(split[2])) {
                                    i5 = 3;
                                }
                            }
                            if (split.length >= 5) {
                                if ("c1".equals(split[4])) {
                                    iArr = new int[]{16219713, 13275258, 16757049, 15582629, 16765248, 16245699, 16768889, 16510934};
                                } else if ("c2".equals(split[4])) {
                                    iArr = new int[]{16219713, 11172960, 16757049, 13150599, 16765248, 14534815, 16768889, 15128242};
                                } else if ("c3".equals(split[4])) {
                                    iArr = new int[]{16219713, 9199944, 16757049, 11371874, 16765248, 12885622, 16768889, 13939080};
                                } else if ("c4".equals(split[4])) {
                                    iArr = new int[]{16219713, 7224364, 16757049, 9591348, 16765248, 10579526, 16768889, 11303506};
                                } else if ("c5".equals(split[4])) {
                                    iArr = new int[]{16219713, 2694162, 16757049, 4663842, 16765248, 5716784, 16768889, 6834492};
                                }
                            }
                        }
                        RLottieDrawable rLottieDrawable = new RLottieDrawable(this.cacheImage.finalFilePath, min, min2, z6, z7, iArr);
                        rLottieDrawable.setAutoRepeat(i5);
                        onPostExecute(rLottieDrawable);
                        return;
                    }
                }
                if (this.cacheImage.animatedFile) {
                    synchronized (this.sync) {
                        if (this.isCancelled) {
                            return;
                        }
                        if (!ImageLoader.AUTOPLAY_FILTER.equals(this.cacheImage.filter) || (this.cacheImage.imageLocation.document instanceof TLRPC.TL_documentEncrypted)) {
                            animatedFileDrawable = new AnimatedFileDrawable(this.cacheImage.finalFilePath, "d".equals(this.cacheImage.filter), 0L, null, null, this.cacheImage.currentAccount, false);
                        } else {
                            animatedFileDrawable = new AnimatedFileDrawable(this.cacheImage.finalFilePath, false, this.cacheImage.size, this.cacheImage.imageLocation.document instanceof TLRPC.Document ? this.cacheImage.imageLocation.document : null, this.cacheImage.parentObject, this.cacheImage.currentAccount, false);
                        }
                        Thread.interrupted();
                        onPostExecute(animatedFileDrawable);
                        return;
                    }
                }
                Long l2 = null;
                boolean z8 = false;
                bitmap = null;
                file = this.cacheImage.finalFilePath;
                boolean z9 = (this.cacheImage.secureDocument == null && (this.cacheImage.encryptionKeyPath == null || file == null || !file.getAbsolutePath().endsWith(".enc"))) ? false : true;
                if (this.cacheImage.secureDocument != null) {
                    secureDocumentKey = this.cacheImage.secureDocument.secureDocumentKey;
                    bArr = (this.cacheImage.secureDocument.secureFile == null || this.cacheImage.secureDocument.secureFile.file_hash == null) ? this.cacheImage.secureDocument.fileHash : this.cacheImage.secureDocument.secureFile.file_hash;
                } else {
                    secureDocumentKey = null;
                    bArr = null;
                }
                boolean z10 = true;
                String str = null;
                if (this.cacheImage.imageLocation.path != null) {
                    String str2 = this.cacheImage.imageLocation.path;
                    if (str2.startsWith("thumb://")) {
                        int indexOf = str2.indexOf(LogUtils.COLON, 8);
                        if (indexOf >= 0) {
                            l2 = Long.valueOf(Long.parseLong(str2.substring(8, indexOf)));
                            z8 = false;
                            str = str2.substring(indexOf + 1);
                        }
                        z10 = false;
                        l = l2;
                    } else if (str2.startsWith("vthumb://")) {
                        int indexOf2 = str2.indexOf(LogUtils.COLON, 9);
                        if (indexOf2 >= 0) {
                            l2 = Long.valueOf(Long.parseLong(str2.substring(9, indexOf2)));
                            z8 = true;
                        }
                        z10 = false;
                        l = l2;
                    } else if (!str2.startsWith("http")) {
                        z10 = false;
                        l = null;
                    }
                    options = new BitmapFactory.Options();
                    options.inSampleSize = 1;
                    f = 0.0f;
                    float f5 = 0.0f;
                    int i6 = 0;
                    boolean z11 = ImageLoader.this.canForce8888;
                    ?? r26 = 1065353216;
                    r26 = 1065353216;
                    r26 = 1065353216;
                    r26 = 1065353216;
                    r26 = 1065353216;
                    r26 = 1065353216;
                    if (this.cacheImage.filter == null) {
                        String[] split2 = this.cacheImage.filter.split("_");
                        if (split2.length >= 2) {
                            try {
                                f = Float.parseFloat(split2[0]) * AndroidUtilities.density;
                                f5 = Float.parseFloat(split2[1]) * AndroidUtilities.density;
                            } catch (Throwable th) {
                                th = th;
                                z2 = false;
                                FileLog.e(th);
                                f2 = f5;
                                i = i6;
                                bitmap2 = r26;
                                i2 = 0;
                                if (this.cacheImage.imageType != 1) {
                                }
                                Thread.interrupted();
                                if (z3) {
                                }
                                onPostExecute(bitmap != null ? new ExtendedBitmapDrawable(bitmap, z3, i3) : null);
                            }
                        }
                        if (this.cacheImage.filter.contains("b2")) {
                            i6 = 3;
                        } else if (this.cacheImage.filter.contains("b1")) {
                            i6 = 2;
                        } else if (this.cacheImage.filter.contains("b")) {
                            i6 = 1;
                        }
                        z = this.cacheImage.filter.contains("i");
                        if (this.cacheImage.filter.contains("f")) {
                            z11 = true;
                        }
                        if (0 != 0 || f == 0.0f || f5 == 0.0f) {
                            bitmap3 = null;
                            z2 = false;
                        } else {
                            options.inJustDecodeBounds = true;
                            if (l == null || str != null) {
                                bitmap3 = null;
                                z2 = false;
                                if (secureDocumentKey != null) {
                                    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
                                    int length2 = (int) randomAccessFile.length();
                                    byte[] bArr6 = (byte[]) ImageLoader.bytesLocal.get();
                                    byte[] bArr7 = (bArr6 == null || bArr6.length < length2) ? null : bArr6;
                                    if (bArr7 == null) {
                                        byte[] bArr8 = new byte[length2];
                                        bArr7 = bArr8;
                                        bArr6 = bArr8;
                                        ImageLoader.bytesLocal.set(bArr6);
                                    }
                                    randomAccessFile.readFully(bArr7, 0, length2);
                                    randomAccessFile.close();
                                    EncryptedFileInputStream.decryptBytesWithKeyFile(bArr7, 0, length2, secureDocumentKey);
                                    c = (bArr == null || !Arrays.equals(Utilities.computeSHA256(bArr7, 0, length2), bArr)) ? (char) 1 : (char) 0;
                                    int i7 = bArr7[0] & UByte.MAX_VALUE;
                                    int i8 = length2 - i7;
                                    if (c == 0) {
                                        BitmapFactory.decodeByteArray(bArr7, i7, i8, options);
                                    }
                                } else {
                                    FileInputStream encryptedFileInputStream = z9 ? new EncryptedFileInputStream(file, this.cacheImage.encryptionKeyPath) : new FileInputStream(file);
                                    BitmapFactory.decodeStream(encryptedFileInputStream, null, options);
                                    encryptedFileInputStream.close();
                                }
                            } else if (z8) {
                                z2 = false;
                                try {
                                    bitmap3 = null;
                                    MediaStore.Video.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), l.longValue(), 1, options);
                                } catch (Throwable th2) {
                                    th = th2;
                                    bitmap = null;
                                    FileLog.e(th);
                                    f2 = f5;
                                    i = i6;
                                    bitmap2 = r26;
                                    i2 = 0;
                                    if (this.cacheImage.imageType != 1) {
                                    }
                                    Thread.interrupted();
                                    if (z3) {
                                    }
                                    onPostExecute(bitmap != null ? new ExtendedBitmapDrawable(bitmap, z3, i3) : null);
                                }
                            } else {
                                bitmap3 = null;
                                z2 = false;
                                MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), l.longValue(), 1, options);
                            }
                            float f6 = options.outWidth;
                            float f7 = options.outHeight;
                            float min3 = (f < f5 || f6 <= f7) ? Math.min(f6 / f, f7 / f5) : Math.max(f6 / f, f7 / f5);
                            if (min3 < 1.2f) {
                                min3 = 1.0f;
                            }
                            options.inJustDecodeBounds = false;
                            if (min3 <= 1.0f || (f6 <= f && f7 <= f5)) {
                                options.inSampleSize = (int) min3;
                            } else {
                                int i9 = 1;
                                do {
                                    i9 *= 2;
                                } while (i9 * 2 < min3);
                                options.inSampleSize = i9;
                            }
                        }
                    } else {
                        bitmap3 = null;
                        z2 = false;
                        if (str != null) {
                            options.inJustDecodeBounds = true;
                            options.inPreferredConfig = z11 ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
                            FileInputStream fileInputStream2 = new FileInputStream(file);
                            bitmap = BitmapFactory.decodeStream(fileInputStream2, null, options);
                            try {
                                fileInputStream2.close();
                                int i10 = options.outWidth;
                                int i11 = options.outHeight;
                                options.inJustDecodeBounds = false;
                                float max = Math.max(i10 / 200, i11 / 200);
                                if (max < 1.0f) {
                                    max = 1.0f;
                                }
                                if (max > 1.0f) {
                                    int i12 = 1;
                                    while (true) {
                                        i12 *= 2;
                                        i4 = i10;
                                        if (i12 * 2 >= max) {
                                            break;
                                        } else {
                                            i10 = i4;
                                        }
                                    }
                                    options.inSampleSize = i12;
                                    r26 = i4;
                                } else {
                                    r26 = i10;
                                    options.inSampleSize = (int) max;
                                }
                                f2 = f5;
                                i = i6;
                                bitmap2 = r26;
                            } catch (Throwable th3) {
                                th = th3;
                                FileLog.e(th);
                                f2 = f5;
                                i = i6;
                                bitmap2 = r26;
                                i2 = 0;
                                if (this.cacheImage.imageType != 1) {
                                }
                                Thread.interrupted();
                                if (z3) {
                                }
                                onPostExecute(bitmap != null ? new ExtendedBitmapDrawable(bitmap, z3, i3) : null);
                            }
                            i2 = 0;
                            if (this.cacheImage.imageType != 1) {
                                try {
                                    ImageLoader.this.lastCacheOutTime = System.currentTimeMillis();
                                    try {
                                    } catch (Throwable th4) {
                                        th = th4;
                                        bitmap = bitmap2;
                                        z3 = z2;
                                        f3 = c;
                                    }
                                } catch (Throwable th5) {
                                    th = th5;
                                    f3 = f2;
                                    z3 = z2;
                                }
                                synchronized (this.sync) {
                                    try {
                                        if (this.isCancelled) {
                                            try {
                                                return;
                                            } catch (Throwable th6) {
                                                th = th6;
                                                while (true) {
                                                    try {
                                                        break;
                                                    } catch (Throwable th7) {
                                                        th = th7;
                                                    }
                                                }
                                                throw th;
                                            }
                                        }
                                        try {
                                            if (0 != 0) {
                                                RandomAccessFile randomAccessFile2 = new RandomAccessFile(file, "r");
                                                MappedByteBuffer map = randomAccessFile2.getChannel().map(FileChannel.MapMode.READ_ONLY, 0L, file.length());
                                                BitmapFactory.Options options2 = new BitmapFactory.Options();
                                                Bitmap bitmap4 = bitmap;
                                                try {
                                                    options2.inJustDecodeBounds = true;
                                                    f3 = f2;
                                                    Utilities.loadWebpImage(null, map, map.limit(), options2, true);
                                                    bitmap = Bitmaps.createBitmap(options2.outWidth, options2.outHeight, Bitmap.Config.ARGB_8888);
                                                    Utilities.loadWebpImage(bitmap, map, map.limit(), null, !options.inPurgeable);
                                                    randomAccessFile2.close();
                                                } catch (Throwable th8) {
                                                    th = th8;
                                                    f3 = f2;
                                                    bitmap = bitmap4;
                                                    z3 = z2;
                                                    FileLog.e(th);
                                                    i3 = 0;
                                                    Thread.interrupted();
                                                    if (z3) {
                                                    }
                                                    onPostExecute(bitmap != null ? new ExtendedBitmapDrawable(bitmap, z3, i3) : null);
                                                }
                                            } else {
                                                float f8 = f2;
                                                Bitmap bitmap5 = bitmap;
                                                if (!options.inPurgeable && secureDocumentKey == null) {
                                                    FileInputStream encryptedFileInputStream2 = z9 ? new EncryptedFileInputStream(file, this.cacheImage.encryptionKeyPath) : new FileInputStream(file);
                                                    bitmap = BitmapFactory.decodeStream(encryptedFileInputStream2, null, options);
                                                    encryptedFileInputStream2.close();
                                                    f3 = f8;
                                                }
                                                RandomAccessFile randomAccessFile3 = new RandomAccessFile(file, "r");
                                                int length3 = (int) randomAccessFile3.length();
                                                int i13 = 0;
                                                byte[] bArr9 = (byte[]) ImageLoader.bytesThumbLocal.get();
                                                byte[] bArr10 = (bArr9 == null || bArr9.length < length3) ? null : bArr9;
                                                if (bArr10 == null) {
                                                    byte[] bArr11 = new byte[length3];
                                                    bArr10 = bArr11;
                                                    ImageLoader.bytesThumbLocal.set(bArr11);
                                                }
                                                randomAccessFile3.readFully(bArr10, 0, length3);
                                                randomAccessFile3.close();
                                                if (secureDocumentKey != null) {
                                                    EncryptedFileInputStream.decryptBytesWithKeyFile(bArr10, 0, length3, secureDocumentKey);
                                                    r33 = bArr == null || !Arrays.equals(Utilities.computeSHA256(bArr10, 0, length3), bArr);
                                                    i13 = bArr10[0] & UByte.MAX_VALUE;
                                                    length3 -= i13;
                                                } else if (z9) {
                                                    EncryptedFileInputStream.decryptBytesWithKeyFile(bArr10, 0, length3, this.cacheImage.encryptionKeyPath);
                                                    if (r33) {
                                                        bitmap = BitmapFactory.decodeByteArray(bArr10, i13, length3, options);
                                                        f3 = f8;
                                                    } else {
                                                        bitmap = bitmap5;
                                                        f3 = f8;
                                                    }
                                                }
                                                if (r33) {
                                                }
                                            }
                                            if (bitmap == null) {
                                                if (file.length() == 0 || this.cacheImage.filter == null) {
                                                    file.delete();
                                                }
                                                z3 = z2;
                                            } else {
                                                if (this.cacheImage.filter != null) {
                                                    float width = bitmap.getWidth();
                                                    float height = bitmap.getHeight();
                                                    if (!options.inPurgeable && f != 0.0f && width != f && width > 20.0f + f) {
                                                        Bitmap createScaledBitmap2 = Bitmaps.createScaledBitmap(bitmap, (int) f, (int) (height / (width / f)), true);
                                                        if (bitmap != createScaledBitmap2) {
                                                            bitmap.recycle();
                                                            bitmap = createScaledBitmap2;
                                                        }
                                                    }
                                                }
                                                if (z) {
                                                    z3 = Utilities.needInvert(bitmap, options.inPurgeable ? 0 : 1, bitmap.getWidth(), bitmap.getHeight(), bitmap.getRowBytes()) != 0;
                                                } else {
                                                    z3 = z2;
                                                }
                                                try {
                                                    if (i == 1) {
                                                        if (bitmap.getConfig() == Bitmap.Config.ARGB_8888) {
                                                            Utilities.blurBitmap(bitmap, 3, options.inPurgeable ? 0 : 1, bitmap.getWidth(), bitmap.getHeight(), bitmap.getRowBytes());
                                                        }
                                                    } else if (i == 2) {
                                                        if (bitmap.getConfig() == Bitmap.Config.ARGB_8888) {
                                                            Utilities.blurBitmap(bitmap, 1, options.inPurgeable ? 0 : 1, bitmap.getWidth(), bitmap.getHeight(), bitmap.getRowBytes());
                                                        }
                                                    } else if (i == 3) {
                                                        if (bitmap.getConfig() == Bitmap.Config.ARGB_8888) {
                                                            Utilities.blurBitmap(bitmap, 7, options.inPurgeable ? 0 : 1, bitmap.getWidth(), bitmap.getHeight(), bitmap.getRowBytes());
                                                            Utilities.blurBitmap(bitmap, 7, options.inPurgeable ? 0 : 1, bitmap.getWidth(), bitmap.getHeight(), bitmap.getRowBytes());
                                                            Utilities.blurBitmap(bitmap, 7, options.inPurgeable ? 0 : 1, bitmap.getWidth(), bitmap.getHeight(), bitmap.getRowBytes());
                                                        }
                                                    } else if (i == 0) {
                                                        if (options.inPurgeable) {
                                                            Utilities.pinBitmap(bitmap);
                                                        }
                                                    }
                                                } catch (Throwable th9) {
                                                    th = th9;
                                                    f3 = f3;
                                                    FileLog.e(th);
                                                    i3 = 0;
                                                    Thread.interrupted();
                                                    if (z3) {
                                                    }
                                                    onPostExecute(bitmap != null ? new ExtendedBitmapDrawable(bitmap, z3, i3) : null);
                                                }
                                            }
                                        } catch (Throwable th10) {
                                            th = th10;
                                            z3 = z2;
                                            f3 = c;
                                        }
                                        i3 = 0;
                                    } catch (Throwable th11) {
                                        th = th11;
                                    }
                                }
                            } else {
                                f4 = f2;
                                Bitmap bitmap6 = bitmap;
                                z4 = z10;
                                int i14 = l != null ? 0 : 20;
                                try {
                                    if (i14 != 0) {
                                        try {
                                            if (ImageLoader.this.lastCacheOutTime != 0) {
                                                bArr2 = bArr;
                                                if (ImageLoader.this.lastCacheOutTime > System.currentTimeMillis() - i14) {
                                                }
                                                ImageLoader.this.lastCacheOutTime = System.currentTimeMillis();
                                                synchronized (this.sync) {
                                                    try {
                                                        if (this.isCancelled) {
                                                            try {
                                                                return;
                                                            } catch (Throwable th12) {
                                                                th = th12;
                                                                while (true) {
                                                                    try {
                                                                        break;
                                                                    } catch (Throwable th13) {
                                                                        th = th13;
                                                                    }
                                                                }
                                                                throw th;
                                                            }
                                                        }
                                                    } catch (Throwable th14) {
                                                        th = th14;
                                                    }
                                                }
                                                try {
                                                    break;
                                                    throw th;
                                                } catch (Throwable th15) {
                                                    i3 = 0;
                                                    bitmap = bitmap6;
                                                    z3 = z2;
                                                }
                                            }
                                        } catch (Throwable th16) {
                                            i3 = 0;
                                            bitmap = bitmap6;
                                            z3 = z2;
                                        }
                                    }
                                    ImageLoader.this.lastCacheOutTime = System.currentTimeMillis();
                                    synchronized (this.sync) {
                                    }
                                } catch (Throwable th17) {
                                    i3 = 0;
                                    bitmap = bitmap6;
                                    z3 = z2;
                                }
                                bArr2 = bArr;
                            }
                            Thread.interrupted();
                            if (z3 && i3 == 0) {
                                onPostExecute(bitmap != null ? new BitmapDrawable(bitmap) : null);
                                return;
                            } else {
                                onPostExecute(bitmap != null ? new ExtendedBitmapDrawable(bitmap, z3, i3) : null);
                            }
                        }
                    }
                    bitmap = bitmap3;
                    f2 = f5;
                    i = i6;
                    bitmap2 = r26;
                    i2 = 0;
                    if (this.cacheImage.imageType != 1) {
                    }
                    Thread.interrupted();
                    if (z3) {
                    }
                    onPostExecute(bitmap != null ? new ExtendedBitmapDrawable(bitmap, z3, i3) : null);
                }
                l = null;
                options = new BitmapFactory.Options();
                options.inSampleSize = 1;
                f = 0.0f;
                float f52 = 0.0f;
                int i62 = 0;
                boolean z112 = ImageLoader.this.canForce8888;
                ?? r262 = 1065353216;
                r262 = 1065353216;
                r262 = 1065353216;
                r262 = 1065353216;
                r262 = 1065353216;
                r262 = 1065353216;
                if (this.cacheImage.filter == null) {
                }
                bitmap = bitmap3;
                f2 = f52;
                i = i62;
                bitmap2 = r262;
                i2 = 0;
                if (this.cacheImage.imageType != 1) {
                }
                Thread.interrupted();
                if (z3) {
                }
                onPostExecute(bitmap != null ? new ExtendedBitmapDrawable(bitmap, z3, i3) : null);
            }
            fileInputStream.getChannel().position(0L);
            bitmap = BitmapFactory.decodeStream(fileInputStream, null, options);
            fileInputStream.close();
            if (bitmap == null) {
                if (z4 && (file.length() == 0 || this.cacheImage.filter == null)) {
                    file.delete();
                }
                z3 = z2;
            } else {
                boolean z12 = false;
                try {
                    if (this.cacheImage.filter != null) {
                        float width2 = bitmap.getWidth();
                        float height2 = bitmap.getHeight();
                        if (!options.inPurgeable && f != 0.0f && width2 != f && width2 > 20.0f + f) {
                            if (width2 <= height2 || f <= f4) {
                                try {
                                    createScaledBitmap = Bitmaps.createScaledBitmap(bitmap, (int) (width2 / (height2 / f4)), (int) f4, true);
                                } catch (Throwable th18) {
                                    i3 = i2;
                                    z3 = z2;
                                }
                            } else {
                                try {
                                    createScaledBitmap = Bitmaps.createScaledBitmap(bitmap, (int) f, (int) (height2 / (width2 / f)), true);
                                } catch (Throwable th19) {
                                    i3 = i2;
                                    z3 = z2;
                                }
                            }
                            if (bitmap != createScaledBitmap) {
                                bitmap.recycle();
                                bitmap = createScaledBitmap;
                            }
                        }
                        if (bitmap != null) {
                            if (z) {
                                Bitmap bitmap7 = bitmap;
                                try {
                                    z5 = false;
                                    if (bitmap.getWidth() * bitmap.getHeight() > 22500) {
                                        bitmap7 = Bitmaps.createScaledBitmap(bitmap, 100, 100, false);
                                    }
                                    try {
                                        try {
                                            boolean z13 = Utilities.needInvert(bitmap7, options.inPurgeable ? 0 : 1, bitmap7.getWidth(), bitmap7.getHeight(), bitmap7.getRowBytes()) != 0;
                                            if (bitmap7 != bitmap) {
                                                try {
                                                    bitmap7.recycle();
                                                } catch (Throwable th20) {
                                                    z3 = z13;
                                                    i3 = i2;
                                                }
                                            }
                                            z3 = z13;
                                        } catch (Throwable th21) {
                                            i3 = i2;
                                            z3 = z2;
                                        }
                                    } catch (Throwable th22) {
                                        i3 = i2;
                                        z3 = z2;
                                    }
                                } catch (Throwable th23) {
                                    i3 = i2;
                                    z3 = z2;
                                }
                            } else {
                                z5 = false;
                                z3 = z2;
                            }
                            if (i == 0 || height2 >= 100.0f || width2 >= 100.0f) {
                                z12 = z5;
                            } else {
                                try {
                                    if (bitmap.getConfig() == Bitmap.Config.ARGB_8888) {
                                        Utilities.blurBitmap(bitmap, 3, options.inPurgeable ? 0 : 1, bitmap.getWidth(), bitmap.getHeight(), bitmap.getRowBytes());
                                    }
                                    z12 = true;
                                } catch (Throwable th24) {
                                    i3 = i2;
                                }
                            }
                        } else {
                            z3 = z2;
                        }
                    } else {
                        z3 = z2;
                    }
                    if (!z12 && options.inPurgeable) {
                        Utilities.pinBitmap(bitmap);
                    }
                } catch (Throwable th25) {
                    i3 = i2;
                    z3 = z2;
                }
            }
            i3 = i2;
            Thread.interrupted();
            if (z3) {
            }
            onPostExecute(bitmap != null ? new ExtendedBitmapDrawable(bitmap, z3, i3) : null);
        }

        private void onPostExecute(final Drawable drawable) {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.CacheOutTask.this.m261x3728154c(drawable);
                }
            });
        }

        public void m261x3728154c(Drawable drawable) {
            Drawable toSet = null;
            String decrementKey = null;
            if (drawable instanceof RLottieDrawable) {
                RLottieDrawable lottieDrawable = (RLottieDrawable) drawable;
                toSet = (Drawable) ImageLoader.this.lottieMemCache.get(this.cacheImage.key);
                if (toSet == null) {
                    ImageLoader.this.lottieMemCache.put(this.cacheImage.key, lottieDrawable);
                    toSet = lottieDrawable;
                } else {
                    lottieDrawable.recycle();
                }
                if (toSet != null) {
                    ImageLoader.this.incrementUseCount(this.cacheImage.key);
                    decrementKey = this.cacheImage.key;
                }
            } else if (drawable instanceof AnimatedFileDrawable) {
                toSet = drawable;
            } else if (drawable instanceof BitmapDrawable) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
                toSet = (Drawable) ImageLoader.this.memCache.get(this.cacheImage.key);
                if (toSet == null) {
                    ImageLoader.this.memCache.put(this.cacheImage.key, bitmapDrawable);
                    toSet = bitmapDrawable;
                } else {
                    Bitmap image = bitmapDrawable.getBitmap();
                    image.recycle();
                }
                if (toSet != null) {
                    ImageLoader.this.incrementUseCount(this.cacheImage.key);
                    decrementKey = this.cacheImage.key;
                }
            }
            final Drawable toSetFinal = toSet;
            final String decrementKetFinal = decrementKey;
            ImageLoader.this.imageLoadQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.CacheOutTask.this.m260x457e6f2d(toSetFinal, decrementKetFinal);
                }
            });
        }

        public void m260x457e6f2d(Drawable toSetFinal, String decrementKetFinal) {
            this.cacheImage.setImageAndClear(toSetFinal, decrementKetFinal);
        }

        public void cancel() {
            synchronized (this.sync) {
                try {
                    this.isCancelled = true;
                    Thread thread = this.runningThread;
                    if (thread != null) {
                        thread.interrupt();
                    }
                } catch (Exception e) {
                }
            }
        }
    }

    public class CacheImage {
        protected boolean animatedFile;
        protected ArtworkLoadTask artworkTask;
        protected CacheOutTask cacheTask;
        protected int currentAccount;
        protected File encryptionKeyPath;
        protected String ext;
        protected String filter;
        protected ArrayList<String> filters;
        protected File finalFilePath;
        protected HttpImageTask httpTask;
        protected ImageLocation imageLocation;
        protected ArrayList<ImageReceiver> imageReceiverArray;
        protected ArrayList<Integer> imageReceiverGuidsArray;
        protected int imageType;
        protected ArrayList<Integer> imageTypes;
        protected String key;
        protected ArrayList<String> keys;
        protected boolean lottieFile;
        protected Object parentObject;
        protected SecureDocument secureDocument;
        protected int size;
        protected File tempFilePath;
        protected String url;

        private CacheImage() {
            this.imageReceiverArray = new ArrayList<>();
            this.imageReceiverGuidsArray = new ArrayList<>();
            this.keys = new ArrayList<>();
            this.filters = new ArrayList<>();
            this.imageTypes = new ArrayList<>();
        }

        public void addImageReceiver(ImageReceiver imageReceiver, String key, String filter, int type, int guid) {
            int index = this.imageReceiverArray.indexOf(imageReceiver);
            if (index >= 0) {
                this.imageReceiverGuidsArray.set(index, Integer.valueOf(guid));
                return;
            }
            this.imageReceiverArray.add(imageReceiver);
            this.imageReceiverGuidsArray.add(Integer.valueOf(guid));
            this.keys.add(key);
            this.filters.add(filter);
            this.imageTypes.add(Integer.valueOf(type));
            ImageLoader.this.imageLoadingByTag.put(imageReceiver.getTag(type), this);
        }

        public void replaceImageReceiver(ImageReceiver imageReceiver, String key, String filter, int type, int guid) {
            int index = this.imageReceiverArray.indexOf(imageReceiver);
            if (index == -1) {
                return;
            }
            if (this.imageTypes.get(index).intValue() != type) {
                ArrayList<ImageReceiver> arrayList = this.imageReceiverArray;
                index = arrayList.subList(index + 1, arrayList.size()).indexOf(imageReceiver);
                if (index == -1) {
                    return;
                }
            }
            this.imageReceiverGuidsArray.set(index, Integer.valueOf(guid));
            this.keys.set(index, key);
            this.filters.set(index, filter);
        }

        public void removeImageReceiver(ImageReceiver imageReceiver) {
            int currentImageType = this.imageType;
            int a = 0;
            while (a < this.imageReceiverArray.size()) {
                ImageReceiver obj = this.imageReceiverArray.get(a);
                if (obj == null || obj == imageReceiver) {
                    this.imageReceiverArray.remove(a);
                    this.imageReceiverGuidsArray.remove(a);
                    this.keys.remove(a);
                    this.filters.remove(a);
                    currentImageType = this.imageTypes.remove(a).intValue();
                    if (obj != null) {
                        ImageLoader.this.imageLoadingByTag.remove(obj.getTag(currentImageType));
                    }
                    a--;
                }
                a++;
            }
            if (this.imageReceiverArray.isEmpty()) {
                if (this.imageLocation != null && !ImageLoader.this.forceLoadingImages.containsKey(this.key)) {
                    if (this.imageLocation.location != null) {
                        FileLoader.getInstance(this.currentAccount).cancelLoadFile(this.imageLocation.location, this.ext);
                    } else if (this.imageLocation.document != null) {
                        FileLoader.getInstance(this.currentAccount).cancelLoadFile(this.imageLocation.document);
                    } else if (this.imageLocation.secureDocument != null) {
                        FileLoader.getInstance(this.currentAccount).cancelLoadFile(this.imageLocation.secureDocument);
                    } else if (this.imageLocation.webFile != null) {
                        FileLoader.getInstance(this.currentAccount).cancelLoadFile(this.imageLocation.webFile);
                    }
                }
                if (this.cacheTask != null) {
                    if (currentImageType == 1) {
                        ImageLoader.this.cacheThumbOutQueue.cancelRunnable(this.cacheTask);
                    } else {
                        ImageLoader.this.cacheOutQueue.cancelRunnable(this.cacheTask);
                    }
                    this.cacheTask.cancel();
                    this.cacheTask = null;
                }
                if (this.httpTask != null) {
                    ImageLoader.this.httpTasks.remove(this.httpTask);
                    this.httpTask.cancel(true);
                    this.httpTask = null;
                }
                if (this.artworkTask != null) {
                    ImageLoader.this.artworkTasks.remove(this.artworkTask);
                    this.artworkTask.cancel(true);
                    this.artworkTask = null;
                }
                if (this.url != null) {
                    ImageLoader.this.imageLoadingByUrl.remove(this.url);
                }
                if (this.key != null) {
                    ImageLoader.this.imageLoadingByKeys.remove(this.key);
                }
            }
        }

        public void setImageAndClear(final Drawable image, final String decrementKey) {
            if (image != null) {
                final ArrayList<ImageReceiver> finalImageReceiverArray = new ArrayList<>(this.imageReceiverArray);
                final ArrayList<Integer> finalImageReceiverGuidsArray = new ArrayList<>(this.imageReceiverGuidsArray);
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public final void run() {
                        ImageLoader.CacheImage.this.m259x6ae2f382(image, finalImageReceiverArray, finalImageReceiverGuidsArray, decrementKey);
                    }
                });
            }
            for (int a = 0; a < this.imageReceiverArray.size(); a++) {
                ImageReceiver imageReceiver = this.imageReceiverArray.get(a);
                ImageLoader.this.imageLoadingByTag.remove(imageReceiver.getTag(this.imageType));
            }
            this.imageReceiverArray.clear();
            this.imageReceiverGuidsArray.clear();
            if (this.url != null) {
                ImageLoader.this.imageLoadingByUrl.remove(this.url);
            }
            if (this.key != null) {
                ImageLoader.this.imageLoadingByKeys.remove(this.key);
            }
        }

        public void m259x6ae2f382(Drawable image, ArrayList finalImageReceiverArray, ArrayList finalImageReceiverGuidsArray, String decrementKey) {
            if (image instanceof AnimatedFileDrawable) {
                boolean imageSet = false;
                AnimatedFileDrawable fileDrawable = (AnimatedFileDrawable) image;
                int a = 0;
                while (a < finalImageReceiverArray.size()) {
                    ImageReceiver imgView = (ImageReceiver) finalImageReceiverArray.get(a);
                    AnimatedFileDrawable toSet = a == 0 ? fileDrawable : fileDrawable.makeCopy();
                    if (imgView.setImageBitmapByKey(toSet, this.key, this.imageType, false, ((Integer) finalImageReceiverGuidsArray.get(a)).intValue())) {
                        if (toSet == fileDrawable) {
                            imageSet = true;
                        }
                    } else if (toSet != fileDrawable) {
                        toSet.recycle();
                    }
                    a++;
                }
                if (!imageSet) {
                    fileDrawable.recycle();
                }
            } else {
                for (int a2 = 0; a2 < finalImageReceiverArray.size(); a2++) {
                    ImageReceiver imgView2 = (ImageReceiver) finalImageReceiverArray.get(a2);
                    imgView2.setImageBitmapByKey(image, this.key, this.imageTypes.get(a2).intValue(), false, ((Integer) finalImageReceiverGuidsArray.get(a2)).intValue());
                }
            }
            if (decrementKey != null) {
                ImageLoader.this.decrementUseCount(decrementKey);
            }
        }
    }

    public static ImageLoader getInstance() {
        ImageLoader localInstance = Instance;
        if (localInstance == null) {
            synchronized (ImageLoader.class) {
                localInstance = Instance;
                if (localInstance == null) {
                    ImageLoader imageLoader = new ImageLoader();
                    localInstance = imageLoader;
                    Instance = imageLoader;
                }
            }
        }
        return localInstance;
    }

    public ImageLoader() {
        int maxSize;
        this.thumbGeneratingQueue.setPriority(1);
        int memoryClass = ((ActivityManager) ApplicationLoader.applicationContext.getSystemService("activity")).getMemoryClass();
        boolean z = memoryClass >= 192;
        this.canForce8888 = z;
        if (z) {
            maxSize = 30;
        } else {
            maxSize = 15;
        }
        int cacheSize = Math.min(maxSize, memoryClass / 7) * 1024 * 1024;
        this.memCache = new LruCache<BitmapDrawable>(cacheSize) {
            @Override
            public int sizeOf(String key, BitmapDrawable value) {
                return value.getBitmap().getByteCount();
            }

            @Override
            public void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) {
                if (ImageLoader.this.ignoreRemoval == null || !ImageLoader.this.ignoreRemoval.equals(key)) {
                    Integer count = (Integer) ImageLoader.this.bitmapUseCounts.get(key);
                    if (count == null || count.intValue() == 0) {
                        Bitmap b = oldValue.getBitmap();
                        if (!b.isRecycled()) {
                            b.recycle();
                        }
                    }
                }
            }
        };
        this.lottieMemCache = new LruCache<RLottieDrawable>(10485760) {
            @Override
            public int sizeOf(String key, RLottieDrawable value) {
                return value.getIntrinsicWidth() * value.getIntrinsicHeight() * 4 * 2;
            }

            @Override
            public void entryRemoved(boolean evicted, String key, RLottieDrawable oldValue, RLottieDrawable newValue) {
                Integer count = (Integer) ImageLoader.this.bitmapUseCounts.get(key);
                if (count == null || count.intValue() == 0) {
                    oldValue.recycle();
                }
            }
        };
        SparseArray<File> mediaDirs = new SparseArray<>();
        File cachePath = AndroidUtilities.getCacheDir();
        if (!cachePath.isDirectory()) {
            try {
                cachePath.mkdirs();
            } catch (Exception e) {
                FileLog.e(e);
            }
        }
        try {
            new File(cachePath, ".nomedia").createNewFile();
        } catch (Exception e2) {
            FileLog.e(e2);
        }
        mediaDirs.put(4, cachePath);
        for (int a = 0; a < 3; a++) {
            int currentAccount = a;
            FileLoader.getInstance(a).setDelegate(new AnonymousClass3(currentAccount));
        }
        FileLoader.setMediaDirs(mediaDirs);
        BroadcastReceiver receiver = new AnonymousClass4();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.MEDIA_BAD_REMOVAL");
        filter.addAction("android.intent.action.MEDIA_CHECKING");
        filter.addAction("android.intent.action.MEDIA_EJECT");
        filter.addAction("android.intent.action.MEDIA_MOUNTED");
        filter.addAction("android.intent.action.MEDIA_NOFS");
        filter.addAction("android.intent.action.MEDIA_REMOVED");
        filter.addAction("android.intent.action.MEDIA_SHARED");
        filter.addAction("android.intent.action.MEDIA_UNMOUNTABLE");
        filter.addAction("android.intent.action.MEDIA_UNMOUNTED");
        filter.addDataScheme("file");
        try {
            ApplicationLoader.applicationContext.registerReceiver(receiver, filter);
        } catch (Throwable th) {
        }
        checkMediaPaths();
    }

    public class AnonymousClass3 implements FileLoader.FileLoaderDelegate {
        final int val$currentAccount;

        AnonymousClass3(int i) {
            this.val$currentAccount = i;
        }

        @Override
        public void fileUploadProgressChanged(final String location, final float progress, final boolean isEncrypted) {
            ImageLoader.this.fileProgresses.put(location, Float.valueOf(progress));
            long currentTime = System.currentTimeMillis();
            if (ImageLoader.this.lastProgressUpdateTime == 0 || ImageLoader.this.lastProgressUpdateTime < currentTime - 500) {
                ImageLoader.this.lastProgressUpdateTime = currentTime;
                final int i = this.val$currentAccount;
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public final void run() {
                        NotificationCenter.getInstance(i).postNotificationName(NotificationCenter.FileUploadProgressChanged, location, Float.valueOf(progress), Boolean.valueOf(isEncrypted));
                    }
                });
            }
        }

        @Override
        public void fileDidUploaded(final String location, final TLRPC.InputFile inputFile, final TLRPC.InputEncryptedFile inputEncryptedFile, final byte[] key, final byte[] iv, final long totalFileSize, final boolean apply) {
            DispatchQueue dispatchQueue = Utilities.stageQueue;
            final int i = this.val$currentAccount;
            dispatchQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.AnonymousClass3.this.m255lambda$fileDidUploaded$2$imczepdgxadmmessengerImageLoader$3(i, location, inputFile, inputEncryptedFile, key, iv, totalFileSize, apply);
                }
            });
        }

        public void m255lambda$fileDidUploaded$2$imczepdgxadmmessengerImageLoader$3(final int currentAccount, final String location, final TLRPC.InputFile inputFile, final TLRPC.InputEncryptedFile inputEncryptedFile, final byte[] key, final byte[] iv, final long totalFileSize, final boolean apply) {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.FileDidUpload, location, inputFile, inputEncryptedFile, key, iv, Long.valueOf(totalFileSize), Boolean.valueOf(apply));
                }
            });
            ImageLoader.this.fileProgresses.remove(location);
        }

        @Override
        public void fileDidFailedUpload(final String location, final boolean isEncrypted) {
            DispatchQueue dispatchQueue = Utilities.stageQueue;
            final int i = this.val$currentAccount;
            dispatchQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.AnonymousClass3.this.m253x758b8cc6(i, location, isEncrypted);
                }
            });
        }

        public void m253x758b8cc6(final int currentAccount, final String location, final boolean isEncrypted) {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.FileDidFailUpload, location, Boolean.valueOf(isEncrypted));
                }
            });
            ImageLoader.this.fileProgresses.remove(location);
        }

        @Override
        public void fileDidLoaded(final String location, final File finalFile, final int type) {
            ImageLoader.this.fileProgresses.remove(location);
            final int i = this.val$currentAccount;
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.AnonymousClass3.this.m254lambda$fileDidLoaded$5$imczepdgxadmmessengerImageLoader$3(finalFile, location, i, type);
                }
            });
        }

        public void m254lambda$fileDidLoaded$5$imczepdgxadmmessengerImageLoader$3(File finalFile, String location, int currentAccount, int type) {
            if (SharedConfig.saveToGallery && ImageLoader.this.appPath != null && finalFile != null && ((location.endsWith(".mp4") || location.endsWith(".jpg")) && finalFile.toString().startsWith(ImageLoader.this.appPath.toString()))) {
                AndroidUtilities.addMediaToGallery(finalFile.toString());
            }
            NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.fileDidLoad, location, finalFile);
            ImageLoader.this.fileDidLoaded(location, finalFile, type);
        }

        @Override
        public void fileDidFailedLoad(final String location, final int canceled) {
            ImageLoader.this.fileProgresses.remove(location);
            final int i = this.val$currentAccount;
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.AnonymousClass3.this.m252lambda$fileDidFailedLoad$6$imczepdgxadmmessengerImageLoader$3(location, canceled, i);
                }
            });
        }

        public void m252lambda$fileDidFailedLoad$6$imczepdgxadmmessengerImageLoader$3(String location, int canceled, int currentAccount) {
            ImageLoader.this.fileDidFailedLoad(location, canceled);
            NotificationCenter.getInstance(currentAccount).postNotificationName(NotificationCenter.fileDidFailToLoad, location, Integer.valueOf(canceled));
        }

        @Override
        public void fileLoadProgressChanged(final String location, final float progress) {
            ImageLoader.this.fileProgresses.put(location, Float.valueOf(progress));
            long currentTime = System.currentTimeMillis();
            if (ImageLoader.this.lastProgressUpdateTime == 0 || ImageLoader.this.lastProgressUpdateTime < currentTime - 500) {
                ImageLoader.this.lastProgressUpdateTime = currentTime;
                final int i = this.val$currentAccount;
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public final void run() {
                        NotificationCenter.getInstance(i).postNotificationName(NotificationCenter.FileLoadProgressChanged, location, Float.valueOf(progress));
                    }
                });
            }
        }
    }

    public class AnonymousClass4 extends BroadcastReceiver {
        AnonymousClass4() {
        }

        @Override
        public void onReceive(Context arg0, Intent intent) {
            if (BuildVars.LOGS_ENABLED) {
                FileLog.d("file system changed");
            }
            Runnable r = new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.AnonymousClass4.this.m256lambda$onReceive$0$imczepdgxadmmessengerImageLoader$4();
                }
            };
            if ("android.intent.action.MEDIA_UNMOUNTED".equals(intent.getAction())) {
                AndroidUtilities.runOnUIThread(r, 1000L);
            } else {
                r.run();
            }
        }

        public void m256lambda$onReceive$0$imczepdgxadmmessengerImageLoader$4() {
            ImageLoader.this.checkMediaPaths();
        }
    }

    public void checkMediaPaths() {
        this.cacheOutQueue.postRunnable(new Runnable() {
            @Override
            public final void run() {
                ImageLoader.this.m244lambda$checkMediaPaths$1$imczepdgxadmmessengerImageLoader();
            }
        });
    }

    public void m244lambda$checkMediaPaths$1$imczepdgxadmmessengerImageLoader() {
        final SparseArray<File> paths = createMediaPaths();
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public final void run() {
                FileLoader.setMediaDirs(paths);
            }
        });
    }

    public void addTestWebFile(String url, WebFile webFile) {
        if (url == null || webFile == null) {
            return;
        }
        this.testWebFile.put(url, webFile);
    }

    public void removeTestWebFile(String url) {
        if (url == null) {
            return;
        }
        this.testWebFile.remove(url);
    }

    public SparseArray<File> createMediaPaths() {
        SparseArray<File> mediaDirs = new SparseArray<>();
        File cachePath = AndroidUtilities.getCacheDir();
        if (!cachePath.isDirectory()) {
            try {
                cachePath.mkdirs();
            } catch (Exception e) {
                FileLog.e(e);
            }
        }
        try {
            new File(cachePath, ".nomedia").createNewFile();
        } catch (Exception e2) {
            FileLog.e(e2);
        }
        mediaDirs.put(4, cachePath);
        if (BuildVars.LOGS_ENABLED) {
            FileLog.d("cache path = " + cachePath);
        }
        try {
            if ("mounted".equals(Environment.getExternalStorageState())) {
                File file = new File(Environment.getExternalStorageDirectory(), "Wmmm");
                this.appPath = file;
                file.mkdirs();
                if (this.appPath.isDirectory()) {
                    try {
                        File imagePath = new File(this.appPath, "Wmmm Images");
                        imagePath.mkdir();
                        if (imagePath.isDirectory() && canMoveFiles(cachePath, imagePath, 0)) {
                            mediaDirs.put(0, imagePath);
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("image path = " + imagePath);
                            }
                        }
                    } catch (Exception e3) {
                        FileLog.e(e3);
                    }
                    try {
                        File videoPath = new File(this.appPath, "Wmmm Video");
                        videoPath.mkdir();
                        if (videoPath.isDirectory() && canMoveFiles(cachePath, videoPath, 2)) {
                            mediaDirs.put(2, videoPath);
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("video path = " + videoPath);
                            }
                        }
                    } catch (Exception e4) {
                        FileLog.e(e4);
                    }
                    try {
                        File audioPath = new File(this.appPath, "Wmmm Audio");
                        audioPath.mkdir();
                        if (audioPath.isDirectory() && canMoveFiles(cachePath, audioPath, 1)) {
                            new File(audioPath, ".nomedia").createNewFile();
                            mediaDirs.put(1, audioPath);
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("audio path = " + audioPath);
                            }
                        }
                    } catch (Exception e5) {
                        FileLog.e(e5);
                    }
                    try {
                        File documentPath = new File(this.appPath, "Wmmm Documents");
                        documentPath.mkdir();
                        if (documentPath.isDirectory() && canMoveFiles(cachePath, documentPath, 3)) {
                            new File(documentPath, ".nomedia").createNewFile();
                            mediaDirs.put(3, documentPath);
                            if (BuildVars.LOGS_ENABLED) {
                                FileLog.d("documents path = " + documentPath);
                            }
                        }
                    } catch (Exception e6) {
                        FileLog.e(e6);
                    }
                }
            } else if (BuildVars.LOGS_ENABLED) {
                FileLog.d("this Android can't rename files");
            }
            SharedConfig.checkSaveToGalleryFiles();
        } catch (Exception e7) {
            FileLog.e(e7);
        }
        return mediaDirs;
    }

    private boolean canMoveFiles(File from, File to, int type) {
        RandomAccessFile file = null;
        File srcFile = null;
        File dstFile = null;
        try {
            try {
                try {
                    if (type == 0) {
                        srcFile = new File(from, "000000000_999999_temp.jpg");
                        dstFile = new File(to, "000000000_999999.jpg");
                    } else if (type == 3) {
                        srcFile = new File(from, "000000000_999999_temp.doc");
                        dstFile = new File(to, "000000000_999999.doc");
                    } else if (type == 1) {
                        srcFile = new File(from, "000000000_999999_temp.ogg");
                        dstFile = new File(to, "000000000_999999.ogg");
                    } else if (type == 2) {
                        srcFile = new File(from, "000000000_999999_temp.mp4");
                        dstFile = new File(to, "000000000_999999.mp4");
                    }
                    byte[] buffer = new byte[1024];
                    srcFile.createNewFile();
                    RandomAccessFile file2 = new RandomAccessFile(srcFile, "rws");
                    file2.write(buffer);
                    file2.close();
                    file = null;
                    boolean canRename = srcFile.renameTo(dstFile);
                    srcFile.delete();
                    dstFile.delete();
                    if (!canRename) {
                        if (0 == 0) {
                            return false;
                        }
                        file.close();
                        return false;
                    }
                    if (0 != 0) {
                        try {
                            file.close();
                        } catch (Exception e) {
                            FileLog.e(e);
                        }
                    }
                    return true;
                } catch (Exception e2) {
                    FileLog.e(e2);
                    if (file == null) {
                        return false;
                    }
                    file.close();
                    return false;
                }
            } catch (Exception e3) {
                FileLog.e(e3);
                return false;
            }
        } catch (Throwable th) {
            if (file != null) {
                try {
                    file.close();
                } catch (Exception e4) {
                    FileLog.e(e4);
                }
            }
            throw th;
        }
    }

    public Float getFileProgress(String location) {
        if (location == null) {
            return null;
        }
        return this.fileProgresses.get(location);
    }

    public String getReplacedKey(String oldKey) {
        if (oldKey == null) {
            return null;
        }
        return this.replacedBitmaps.get(oldKey);
    }

    private void performReplace(String oldKey, String newKey) {
        BitmapDrawable b = this.memCache.get(oldKey);
        this.replacedBitmaps.put(oldKey, newKey);
        if (b != null) {
            BitmapDrawable oldBitmap = this.memCache.get(newKey);
            boolean dontChange = false;
            if (oldBitmap != null && oldBitmap.getBitmap() != null && b.getBitmap() != null) {
                Bitmap oldBitmapObject = oldBitmap.getBitmap();
                Bitmap newBitmapObject = b.getBitmap();
                if (oldBitmapObject.getWidth() > newBitmapObject.getWidth() || oldBitmapObject.getHeight() > newBitmapObject.getHeight()) {
                    dontChange = true;
                }
            }
            if (!dontChange) {
                this.ignoreRemoval = oldKey;
                this.memCache.remove(oldKey);
                this.memCache.put(newKey, b);
                this.ignoreRemoval = null;
            } else {
                this.memCache.remove(oldKey);
            }
        }
        Integer val = this.bitmapUseCounts.get(oldKey);
        if (val != null) {
            this.bitmapUseCounts.put(newKey, val);
            this.bitmapUseCounts.remove(oldKey);
        }
    }

    public void incrementUseCount(String key) {
        Integer count = this.bitmapUseCounts.get(key);
        if (count == null) {
            this.bitmapUseCounts.put(key, 1);
        } else {
            this.bitmapUseCounts.put(key, Integer.valueOf(count.intValue() + 1));
        }
    }

    public boolean decrementUseCount(String key) {
        Integer count = this.bitmapUseCounts.get(key);
        if (count == null) {
            return true;
        }
        if (count.intValue() != 1) {
            this.bitmapUseCounts.put(key, Integer.valueOf(count.intValue() - 1));
            return false;
        }
        this.bitmapUseCounts.remove(key);
        return true;
    }

    public void removeImage(String key) {
        this.bitmapUseCounts.remove(key);
        this.memCache.remove(key);
    }

    public boolean isInMemCache(String key, boolean animated) {
        return animated ? this.lottieMemCache.get(key) != null : this.memCache.get(key) != null;
    }

    public void clearMemory() {
        this.memCache.evictAll();
        this.lottieMemCache.evictAll();
    }

    private void removeFromWaitingForThumb(int TAG, ImageReceiver imageReceiver) {
        String location = this.waitingForQualityThumbByTag.get(TAG);
        if (location != null) {
            ThumbGenerateInfo info = this.waitingForQualityThumb.get(location);
            if (info != null) {
                int index = info.imageReceiverArray.indexOf(imageReceiver);
                if (index >= 0) {
                    info.imageReceiverArray.remove(index);
                    info.imageReceiverGuidsArray.remove(index);
                }
                if (info.imageReceiverArray.isEmpty()) {
                    this.waitingForQualityThumb.remove(location);
                }
            }
            this.waitingForQualityThumbByTag.remove(TAG);
        }
    }

    public void cancelLoadingForImageReceiver(final ImageReceiver imageReceiver, final boolean cancelAll) {
        if (imageReceiver == null) {
            return;
        }
        this.imageLoadQueue.postRunnable(new Runnable() {
            @Override
            public final void run() {
                ImageLoader.this.m243xd9fe83b7(cancelAll, imageReceiver);
            }
        });
    }

    public void m243xd9fe83b7(boolean cancelAll, ImageReceiver imageReceiver) {
        int imageType;
        for (int a = 0; a < 3; a++) {
            if (a > 0 && !cancelAll) {
                return;
            }
            if (a == 0) {
                imageType = 1;
            } else if (a == 1) {
                imageType = 0;
            } else {
                imageType = 3;
            }
            int TAG = imageReceiver.getTag(imageType);
            if (TAG != 0) {
                if (a == 0) {
                    removeFromWaitingForThumb(TAG, imageReceiver);
                }
                CacheImage ei = this.imageLoadingByTag.get(TAG);
                if (ei != null) {
                    ei.removeImageReceiver(imageReceiver);
                }
            }
        }
    }

    public BitmapDrawable getAnyImageFromMemory(String key) {
        ArrayList<String> filters;
        BitmapDrawable drawable = this.memCache.get(key);
        if (drawable == null && (filters = this.memCache.getFilterKeys(key)) != null && !filters.isEmpty()) {
            return this.memCache.get(key + "@" + filters.get(0));
        }
        return drawable;
    }

    public BitmapDrawable getImageFromMemory(TLObject fileLocation, String httpUrl, String filter) {
        if (fileLocation == null && httpUrl == null) {
            return null;
        }
        String key = null;
        if (httpUrl != null) {
            key = Utilities.MD5(httpUrl);
        } else if (fileLocation instanceof TLRPC.FileLocation) {
            TLRPC.FileLocation location = (TLRPC.FileLocation) fileLocation;
            key = location.volume_id + "_" + location.local_id;
        } else if (fileLocation instanceof TLRPC.Document) {
            TLRPC.Document location2 = (TLRPC.Document) fileLocation;
            key = location2.dc_id + "_" + location2.id;
        } else if (fileLocation instanceof SecureDocument) {
            SecureDocument location3 = (SecureDocument) fileLocation;
            key = location3.secureFile.dc_id + "_" + location3.secureFile.id;
        } else if (fileLocation instanceof WebFile) {
            key = Utilities.MD5(((WebFile) fileLocation).url);
        }
        if (filter != null) {
            key = key + "@" + filter;
        }
        return this.memCache.get(key);
    }

    public void m249lambda$replaceImageInCache$3$imczepdgxadmmessengerImageLoader(String oldKey, String newKey, ImageLocation newLocation) {
        ArrayList<String> arr = this.memCache.getFilterKeys(oldKey);
        if (arr != null) {
            for (int a = 0; a < arr.size(); a++) {
                String filter = arr.get(a);
                String oldK = oldKey + "@" + filter;
                String newK = newKey + "@" + filter;
                performReplace(oldK, newK);
                NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didReplacedPhotoInMemCache, oldK, newK, newLocation);
            }
            return;
        }
        performReplace(oldKey, newKey);
        NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didReplacedPhotoInMemCache, oldKey, newKey, newLocation);
    }

    public void replaceImageInCache(final String oldKey, final String newKey, final ImageLocation newLocation, boolean post) {
        if (post) {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.this.m249lambda$replaceImageInCache$3$imczepdgxadmmessengerImageLoader(oldKey, newKey, newLocation);
                }
            });
        } else {
            m249lambda$replaceImageInCache$3$imczepdgxadmmessengerImageLoader(oldKey, newKey, newLocation);
        }
    }

    public void putImageToCache(BitmapDrawable bitmap, String key) {
        this.memCache.put(key, bitmap);
    }

    private void generateThumb(int mediaType, File originalPath, ThumbGenerateInfo info) {
        if ((mediaType == 0 || mediaType == 2 || mediaType == 3) && originalPath != null && info != null) {
            String name = FileLoader.getAttachFileName(info.parentDocument);
            ThumbGenerateTask task = this.thumbGenerateTasks.get(name);
            if (task == null) {
                ThumbGenerateTask task2 = new ThumbGenerateTask(mediaType, originalPath, info);
                this.thumbGeneratingQueue.postRunnable(task2);
            }
        }
    }

    public void cancelForceLoadingForImageReceiver(ImageReceiver imageReceiver) {
        final String key;
        if (imageReceiver == null || (key = imageReceiver.getImageKey()) == null) {
            return;
        }
        this.imageLoadQueue.postRunnable(new Runnable() {
            @Override
            public final void run() {
                ImageLoader.this.m242xe4d28a9c(key);
            }
        });
    }

    public void m242xe4d28a9c(String key) {
        this.forceLoadingImages.remove(key);
    }

    private void createLoadOperationForImageReceiver(final ImageReceiver imageReceiver, final String key, final String url, final String ext, final ImageLocation imageLocation, final String filter, final int size, final int cacheType, final int imageType, final int thumb, final int guid) {
        int TAG;
        if (imageReceiver == null || url == null || key == null || imageLocation == null) {
            return;
        }
        int TAG2 = imageReceiver.getTag(imageType);
        if (TAG2 != 0) {
            TAG = TAG2;
        } else {
            int TAG3 = this.lastImageNum;
            imageReceiver.setTag(TAG3, imageType);
            int i = this.lastImageNum + 1;
            this.lastImageNum = i;
            if (i == Integer.MAX_VALUE) {
                this.lastImageNum = 0;
            }
            TAG = TAG3;
        }
        final int finalTag = TAG;
        final boolean finalIsNeedsQualityThumb = imageReceiver.isNeedsQualityThumb();
        final Object parentObject = imageReceiver.getParentObject();
        final TLRPC.Document qualityDocument = imageReceiver.getQulityThumbDocument();
        final boolean shouldGenerateQualityThumb = imageReceiver.isShouldGenerateQualityThumb();
        final int currentAccount = imageReceiver.getCurrentAccount();
        final boolean currentKeyQuality = imageType == 0 && imageReceiver.isCurrentKeyQuality();
        this.imageLoadQueue.postRunnable(new Runnable() {
            @Override
            public final void run() {
                ImageLoader.this.m245x49d08ddd(thumb, url, key, finalTag, imageReceiver, filter, imageType, guid, imageLocation, currentKeyQuality, parentObject, qualityDocument, finalIsNeedsQualityThumb, shouldGenerateQualityThumb, cacheType, size, ext, currentAccount);
            }
        });
    }

    public void m245x49d08ddd(int thumb, String url, String key, int finalTag, ImageReceiver imageReceiver, String filter, int imageType, int guid, ImageLocation imageLocation, boolean currentKeyQuality, Object parentObject, TLRPC.Document qualityDocument, boolean finalIsNeedsQualityThumb, boolean shouldGenerateQualityThumb, int cacheType, int size, String ext, int currentAccount) {
        String str;
        boolean onlyCache;
        TLRPC.Document parentDocument;
        String localPath;
        File cachePath;
        boolean bigThumb;
        boolean cacheFileExists;
        int fileType;
        int fileType2;
        File cacheFile;
        ImageLocation imageLocation2;
        String str2;
        int i;
        boolean onlyCache2;
        boolean cacheFileExists2;
        File cacheFile2;
        int localCacheType;
        boolean cacheFileExists3;
        int fileSize;
        boolean onlyCache3;
        File cacheFile3;
        File cacheFile4;
        int fileSize2;
        CacheImage alreadyLoadingCache;
        CacheImage alreadyLoadingUrl;
        boolean added = false;
        if (thumb != 2) {
            CacheImage alreadyLoadingUrl2 = this.imageLoadingByUrl.get(url);
            CacheImage alreadyLoadingCache2 = this.imageLoadingByKeys.get(key);
            CacheImage alreadyLoadingImage = this.imageLoadingByTag.get(finalTag);
            if (alreadyLoadingImage == null) {
                alreadyLoadingCache = alreadyLoadingCache2;
                alreadyLoadingUrl = alreadyLoadingUrl2;
            } else if (alreadyLoadingImage == alreadyLoadingCache2) {
                added = true;
                alreadyLoadingCache = alreadyLoadingCache2;
                alreadyLoadingUrl = alreadyLoadingUrl2;
            } else if (alreadyLoadingImage == alreadyLoadingUrl2) {
                if (alreadyLoadingCache2 == null) {
                    alreadyLoadingCache = alreadyLoadingCache2;
                    alreadyLoadingUrl = alreadyLoadingUrl2;
                    alreadyLoadingImage.replaceImageReceiver(imageReceiver, key, filter, imageType, guid);
                } else {
                    alreadyLoadingCache = alreadyLoadingCache2;
                    alreadyLoadingUrl = alreadyLoadingUrl2;
                }
                added = true;
            } else {
                alreadyLoadingCache = alreadyLoadingCache2;
                alreadyLoadingUrl = alreadyLoadingUrl2;
                alreadyLoadingImage.removeImageReceiver(imageReceiver);
            }
            if (!added && alreadyLoadingCache != null) {
                alreadyLoadingCache.addImageReceiver(imageReceiver, key, filter, imageType, guid);
                added = true;
            }
            if (!added && alreadyLoadingUrl != null) {
                alreadyLoadingUrl.addImageReceiver(imageReceiver, key, filter, imageType, guid);
                added = true;
            }
        }
        if (!added) {
            boolean onlyCache4 = false;
            File cacheFile5 = null;
            boolean cacheFileExists4 = false;
            if (imageLocation.path != null) {
                String location = imageLocation.path;
                if (!location.startsWith("http") && !location.startsWith("athumb")) {
                    if (location.startsWith("thumb://")) {
                        int idx = location.indexOf(LogUtils.COLON, 8);
                        if (idx >= 0) {
                            cacheFile5 = new File(location.substring(idx + 1));
                        }
                        onlyCache4 = true;
                    } else if (location.startsWith("vthumb://")) {
                        int idx2 = location.indexOf(LogUtils.COLON, 9);
                        if (idx2 < 0) {
                            cacheFile5 = null;
                        } else {
                            cacheFile5 = new File(location.substring(idx2 + 1));
                        }
                        onlyCache4 = true;
                    } else {
                        cacheFile5 = new File(location);
                        onlyCache4 = true;
                    }
                } else {
                    cacheFile5 = null;
                }
                str = "athumb";
            } else if (thumb == 0 && currentKeyQuality) {
                if (!(parentObject instanceof MessageObject)) {
                    onlyCache = true;
                    if (qualityDocument != null) {
                        parentDocument = qualityDocument;
                        File cachePath2 = FileLoader.getPathToAttach(parentDocument, true);
                        if (MessageObject.isVideoDocument(parentDocument)) {
                            fileType2 = 2;
                        } else {
                            fileType2 = 3;
                        }
                        localPath = null;
                        bigThumb = true;
                        cachePath = cachePath2;
                        int i2 = fileType2;
                        cacheFileExists = false;
                        fileType = i2;
                    } else {
                        parentDocument = null;
                        localPath = null;
                        cachePath = null;
                        bigThumb = false;
                        cacheFileExists = false;
                        fileType = 0;
                    }
                } else {
                    MessageObject parentMessageObject = (MessageObject) parentObject;
                    parentDocument = parentMessageObject.getDocument();
                    localPath = parentMessageObject.messageOwner.attachPath;
                    onlyCache = true;
                    cachePath = FileLoader.getPathToMessage(parentMessageObject.messageOwner);
                    int fileType3 = parentMessageObject.getFileType();
                    bigThumb = false;
                    cacheFileExists = false;
                    fileType = fileType3;
                }
                if (parentDocument == null) {
                    str = "athumb";
                    onlyCache4 = onlyCache;
                    cacheFile5 = null;
                    cacheFileExists4 = cacheFileExists;
                } else {
                    if (!finalIsNeedsQualityThumb) {
                        str = "athumb";
                        cacheFile = null;
                    } else {
                        str = "athumb";
                        cacheFile = new File(FileLoader.getDirectory(4), "q_" + parentDocument.dc_id + "_" + parentDocument.id + ".jpg");
                        if (!cacheFile.exists()) {
                            cacheFile = null;
                        } else {
                            cacheFileExists = true;
                        }
                    }
                    File attachPath = null;
                    if (!TextUtils.isEmpty(localPath)) {
                        attachPath = new File(localPath);
                        if (!attachPath.exists()) {
                            attachPath = null;
                        }
                    }
                    if (attachPath == null) {
                        attachPath = cachePath;
                    }
                    if (cacheFile != null) {
                        cacheFile5 = cacheFile;
                        onlyCache4 = onlyCache;
                        cacheFileExists4 = cacheFileExists;
                    } else {
                        String location2 = FileLoader.getAttachFileName(parentDocument);
                        ThumbGenerateInfo info = this.waitingForQualityThumb.get(location2);
                        if (info == null) {
                            info = new ThumbGenerateInfo();
                            info.parentDocument = parentDocument;
                            info.filter = filter;
                            info.big = bigThumb;
                            this.waitingForQualityThumb.put(location2, info);
                        }
                        if (!info.imageReceiverArray.contains(imageReceiver)) {
                            info.imageReceiverArray.add(imageReceiver);
                            info.imageReceiverGuidsArray.add(Integer.valueOf(guid));
                        }
                        this.waitingForQualityThumbByTag.put(finalTag, location2);
                        if (attachPath.exists() && shouldGenerateQualityThumb) {
                            generateThumb(fileType, attachPath, info);
                            return;
                        }
                        return;
                    }
                }
            } else {
                str = "athumb";
                cacheFile5 = null;
                cacheFileExists4 = false;
            }
            if (thumb != 2) {
                boolean isEncrypted = imageLocation.isEncrypted();
                CacheImage img = new CacheImage();
                if (currentKeyQuality) {
                    imageLocation2 = imageLocation;
                } else {
                    imageLocation2 = imageLocation;
                    if (MessageObject.isGifDocument(imageLocation2.webFile) || MessageObject.isGifDocument(imageLocation2.document) || MessageObject.isRoundVideoDocument(imageLocation2.document)) {
                        img.animatedFile = true;
                    } else if (imageLocation2.path != null) {
                        String location3 = imageLocation2.path;
                        if (!location3.startsWith("vthumb") && !location3.startsWith("thumb")) {
                            String trueExt = getHttpUrlExtension(location3, "jpg");
                            if (trueExt.equals("mp4") || trueExt.equals("gif")) {
                                img.animatedFile = true;
                            }
                        }
                    }
                }
                if (cacheFile5 != null) {
                    str2 = url;
                    i = cacheType;
                    onlyCache2 = onlyCache4;
                    cacheFileExists2 = cacheFileExists4;
                    cacheFile2 = cacheFile5;
                } else {
                    int fileSize3 = 0;
                    if (imageLocation2.photoSize instanceof TLRPC.TL_photoStrippedSize) {
                        onlyCache3 = true;
                        str2 = url;
                        i = cacheType;
                    } else if (imageLocation2.secureDocument != null) {
                        img.secureDocument = imageLocation2.secureDocument;
                        onlyCache3 = img.secureDocument.secureFile.dc_id == Integer.MIN_VALUE;
                        str2 = url;
                        cacheFile5 = new File(FileLoader.getDirectory(4), str2);
                        i = cacheType;
                    } else {
                        str2 = url;
                        boolean onlyCache5 = onlyCache4;
                        if (AUTOPLAY_FILTER.equals(filter)) {
                            i = cacheType;
                            cacheFileExists3 = cacheFileExists4;
                            fileSize = 0;
                        } else {
                            i = cacheType;
                            if (i == 0 && size > 0) {
                                if (imageLocation2.path == null && !isEncrypted) {
                                    cacheFileExists3 = cacheFileExists4;
                                    fileSize = 0;
                                }
                                cacheFile5 = new File(FileLoader.getDirectory(4), str2);
                                if (!cacheFile5.exists()) {
                                    cacheFileExists4 = true;
                                    fileSize2 = 0;
                                } else if (i == 2) {
                                    File cacheFile6 = FileLoader.getDirectory(4);
                                    fileSize2 = 0;
                                    cacheFile5 = new File(cacheFile6, str2 + ".enc");
                                    cacheFileExists4 = cacheFileExists4;
                                } else {
                                    fileSize2 = 0;
                                }
                                if (imageLocation2.document != null) {
                                    img.lottieFile = "application/x-tgsticker".equals(imageLocation2.document.mime_type);
                                }
                                onlyCache3 = onlyCache5;
                                fileSize3 = fileSize2;
                            }
                            cacheFile5 = new File(FileLoader.getDirectory(4), str2);
                            if (!cacheFile5.exists()) {
                            }
                            if (imageLocation2.document != null) {
                            }
                            onlyCache3 = onlyCache5;
                            fileSize3 = fileSize2;
                        }
                        if (imageLocation2.document != null) {
                            TLRPC.Document document = imageLocation2.document;
                            if (document instanceof TLRPC.TL_documentEncrypted) {
                                cacheFile3 = new File(FileLoader.getDirectory(4), str2);
                            } else {
                                cacheFile3 = MessageObject.isVideoDocument(document) ? new File(FileLoader.getDirectory(2), str2) : new File(FileLoader.getDirectory(3), str2);
                            }
                            if (AUTOPLAY_FILTER.equals(filter) && !cacheFile3.exists()) {
                                cacheFile4 = new File(FileLoader.getDirectory(4), document.dc_id + "_" + document.id + ".temp");
                            } else {
                                cacheFile4 = cacheFile3;
                            }
                            img.lottieFile = "application/x-tgsticker".equals(document.mime_type);
                            fileSize3 = document.size;
                            cacheFile5 = cacheFile4;
                            onlyCache3 = onlyCache5;
                            cacheFileExists4 = cacheFileExists3;
                        } else if (imageLocation2.webFile != null) {
                            cacheFile5 = new File(FileLoader.getDirectory(3), str2);
                            onlyCache3 = onlyCache5;
                            cacheFileExists4 = cacheFileExists3;
                            fileSize3 = fileSize;
                        } else {
                            cacheFile5 = new File(FileLoader.getDirectory(0), str2);
                            onlyCache3 = onlyCache5;
                            cacheFileExists4 = cacheFileExists3;
                            fileSize3 = fileSize;
                        }
                    }
                    if (!AUTOPLAY_FILTER.equals(filter)) {
                        onlyCache2 = onlyCache3;
                        cacheFile2 = cacheFile5;
                        cacheFileExists2 = cacheFileExists4;
                    } else {
                        img.animatedFile = true;
                        img.size = fileSize3;
                        onlyCache2 = true;
                        cacheFile2 = cacheFile5;
                        cacheFileExists2 = cacheFileExists4;
                    }
                }
                img.imageType = imageType;
                img.key = key;
                img.filter = filter;
                img.imageLocation = imageLocation2;
                img.ext = ext;
                img.currentAccount = currentAccount;
                img.parentObject = parentObject;
                if (imageLocation2.lottieAnimation) {
                    img.lottieFile = true;
                }
                if (i == 2) {
                    img.encryptionKeyPath = new File(FileLoader.getInternalCacheDir(), str2 + ".enc.key");
                }
                int i3 = i;
                img.addImageReceiver(imageReceiver, key, filter, imageType, guid);
                if (onlyCache2 || cacheFileExists2 || cacheFile2.exists()) {
                    img.finalFilePath = cacheFile2;
                    img.imageLocation = imageLocation2;
                    img.cacheTask = new CacheOutTask(img);
                    this.imageLoadingByKeys.put(key, img);
                    if (thumb != 0) {
                        this.cacheThumbOutQueue.postRunnable(img.cacheTask);
                        return;
                    } else {
                        this.cacheOutQueue.postRunnable(img.cacheTask);
                        return;
                    }
                }
                img.url = str2;
                this.imageLoadingByUrl.put(str2, img);
                if (imageLocation2.path != null) {
                    String file = Utilities.MD5(imageLocation2.path);
                    File cacheDir = FileLoader.getDirectory(4);
                    img.tempFilePath = new File(cacheDir, file + "_temp.jpg");
                    img.finalFilePath = cacheFile2;
                    if (imageLocation2.path.startsWith(str)) {
                        img.artworkTask = new ArtworkLoadTask(img);
                        this.artworkTasks.add(img.artworkTask);
                        runArtworkTasks(false);
                        return;
                    } else {
                        img.httpTask = new HttpImageTask(img, size);
                        this.httpTasks.add(img.httpTask);
                        runHttpTasks(false);
                        return;
                    }
                }
                if (imageLocation2.location != null) {
                    if (cacheType == 0 && (size <= 0 || imageLocation2.key != null)) {
                        localCacheType = 1;
                    } else {
                        localCacheType = cacheType;
                    }
                    FileLoader.getInstance(currentAccount).loadFile(imageLocation, parentObject, ext, thumb != 0 ? 2 : 1, localCacheType);
                } else if (imageLocation2.document != null) {
                    FileLoader.getInstance(currentAccount).loadFile(imageLocation2.document, parentObject, thumb != 0 ? 2 : 1, i3);
                } else if (imageLocation2.secureDocument != null) {
                    FileLoader.getInstance(currentAccount).loadFile(imageLocation2.secureDocument, thumb != 0 ? 2 : 1);
                } else if (imageLocation2.webFile != null) {
                    FileLoader.getInstance(currentAccount).loadFile(imageLocation2.webFile, thumb != 0 ? 2 : 1, i3);
                }
                if (imageReceiver.isForceLoding()) {
                    this.forceLoadingImages.put(img.key, 0);
                }
            }
        }
    }

    public void loadImageForImageReceiver(ImageReceiver imageReceiver) {
        boolean thumbSet;
        Object parentObject;
        ImageLocation thumbLocation;
        ImageLocation imageLocation;
        boolean qualityThumb;
        String ext;
        String imageKey;
        String imageKey2;
        ImageLocation mediaLocation;
        String mediaKey;
        String imageKey3;
        ImageLocation imageLocation2;
        int a;
        String thumbUrl;
        String thumbKey;
        String mediaKey2;
        String imageKey4;
        String thumbKey2;
        int imageCacheType;
        int mediaCacheType;
        ImageLocation object;
        String thumbKey3;
        String docExt;
        int idx;
        Drawable drawable;
        Drawable drawable2;
        Drawable drawable3;
        if (imageReceiver == null) {
            return;
        }
        boolean imageSet = false;
        String mediaKey3 = imageReceiver.getMediaKey();
        int guid = imageReceiver.getNewGuid();
        if (mediaKey3 != null) {
            ImageLocation mediaLocation2 = imageReceiver.getMediaLocation();
            if (mediaLocation2 != null && (MessageObject.isAnimatedStickerDocument(mediaLocation2.document) || mediaLocation2.lottieAnimation)) {
                drawable3 = this.lottieMemCache.get(mediaKey3);
            } else {
                Drawable drawable4 = this.memCache.get(mediaKey3);
                if (drawable4 != null) {
                    this.memCache.moveToFront(mediaKey3);
                }
                drawable3 = drawable4;
            }
            if (drawable3 != null) {
                cancelLoadingForImageReceiver(imageReceiver, true);
                imageReceiver.setImageBitmapByKey(drawable3, mediaKey3, 3, true, guid);
                imageSet = true;
                if (!imageReceiver.isForcePreview()) {
                    return;
                }
            }
        }
        String imageKey5 = imageReceiver.getImageKey();
        if (!imageSet && imageKey5 != null) {
            ImageLocation imageLocation3 = imageReceiver.getImageLocation();
            if (imageLocation3 != null && (MessageObject.isAnimatedStickerDocument(imageLocation3.document) || imageLocation3.lottieAnimation)) {
                drawable2 = this.lottieMemCache.get(imageKey5);
            } else {
                Drawable drawable5 = this.memCache.get(imageKey5);
                if (drawable5 != null) {
                    this.memCache.moveToFront(imageKey5);
                }
                drawable2 = drawable5;
            }
            if (drawable2 != null) {
                cancelLoadingForImageReceiver(imageReceiver, true);
                imageReceiver.setImageBitmapByKey(drawable2, imageKey5, 0, true, guid);
                imageSet = true;
                if (!imageReceiver.isForcePreview() && mediaKey3 == null) {
                    return;
                }
            }
        }
        boolean imageSet2 = imageSet;
        String thumbKey4 = imageReceiver.getThumbKey();
        if (thumbKey4 != null) {
            ImageLocation thumbLocation2 = imageReceiver.getThumbLocation();
            if (thumbLocation2 != null && (MessageObject.isAnimatedStickerDocument(thumbLocation2.document) || thumbLocation2.lottieAnimation)) {
                drawable = this.lottieMemCache.get(imageKey5);
            } else {
                Drawable drawable6 = this.memCache.get(thumbKey4);
                if (drawable6 != null) {
                    this.memCache.moveToFront(thumbKey4);
                }
                drawable = drawable6;
            }
            if (drawable != null) {
                imageReceiver.setImageBitmapByKey(drawable, thumbKey4, 1, true, guid);
                cancelLoadingForImageReceiver(imageReceiver, false);
                if (imageSet2 && imageReceiver.isForcePreview()) {
                    return;
                }
                thumbSet = true;
                parentObject = imageReceiver.getParentObject();
                TLRPC.Document qualityDocument = imageReceiver.getQulityThumbDocument();
                thumbLocation = imageReceiver.getThumbLocation();
                String thumbFilter = imageReceiver.getThumbFilter();
                ImageLocation mediaLocation3 = imageReceiver.getMediaLocation();
                String mediaFilter = imageReceiver.getMediaFilter();
                imageLocation = imageReceiver.getImageLocation();
                String imageFilter = imageReceiver.getImageFilter();
                if (imageLocation == null && imageReceiver.isNeedsQualityThumb() && imageReceiver.isCurrentKeyQuality()) {
                    if (!(parentObject instanceof MessageObject)) {
                        MessageObject messageObject = (MessageObject) parentObject;
                        imageLocation = ImageLocation.getForDocument(messageObject.getDocument());
                        qualityThumb = true;
                    } else if (qualityDocument != null) {
                        imageLocation = ImageLocation.getForDocument(qualityDocument);
                        qualityThumb = true;
                    }
                    String thumbKey5 = null;
                    ext = imageReceiver.getExt();
                    if (ext != null) {
                        imageKey = null;
                        imageKey2 = "jpg";
                    } else {
                        imageKey = null;
                        imageKey2 = ext;
                    }
                    boolean saveImageToCache = false;
                    mediaLocation = mediaLocation3;
                    String imageUrl = null;
                    mediaKey = null;
                    String mediaUrl = null;
                    imageKey3 = imageKey;
                    imageLocation2 = imageLocation;
                    a = 0;
                    while (a < 2) {
                        if (a == 0) {
                            object = imageLocation2;
                        } else {
                            object = mediaLocation;
                        }
                        if (object == null) {
                            thumbKey3 = thumbKey5;
                        } else {
                            thumbKey3 = thumbKey5;
                            String key = object.getKey(parentObject, mediaLocation != null ? mediaLocation : imageLocation2);
                            if (key != null) {
                                String url = null;
                                if (object.path != null) {
                                    url = key + "." + getHttpUrlExtension(object.path, "jpg");
                                } else if (object.photoSize instanceof TLRPC.TL_photoStrippedSize) {
                                    url = key + "." + imageKey2;
                                } else if (object.location != null) {
                                    url = key + "." + imageKey2;
                                    if (imageReceiver.getExt() != null || object.location.key != null || (object.location.volume_id == -2147483648L && object.location.local_id < 0)) {
                                        saveImageToCache = true;
                                    }
                                } else if (object.webFile != null) {
                                    String defaultExt = FileLoader.getMimeTypePart(object.webFile.mime_type);
                                    url = key + "." + getHttpUrlExtension(object.webFile.url, defaultExt);
                                } else if (object.secureDocument != null) {
                                    url = key + "." + imageKey2;
                                } else if (object.document != null) {
                                    if (a == 0 && qualityThumb) {
                                        key = "q_" + key;
                                    }
                                    String docExt2 = FileLoader.getDocumentFileName(object.document);
                                    if (docExt2 == null || (idx = docExt2.lastIndexOf(46)) == -1) {
                                        docExt = "";
                                    } else {
                                        docExt = docExt2.substring(idx);
                                    }
                                    if (docExt.length() <= 1) {
                                        if (MimeTypes.VIDEO_MP4.equals(object.document.mime_type)) {
                                            docExt = ".mp4";
                                        } else if ("video/x-matroska".equals(object.document.mime_type)) {
                                            docExt = ".mkv";
                                        } else {
                                            docExt = "";
                                        }
                                    }
                                    url = key + docExt;
                                    saveImageToCache = (MessageObject.isVideoDocument(object.document) || MessageObject.isGifDocument(object.document) || MessageObject.isRoundVideoDocument(object.document) || MessageObject.canPreviewDocument(object.document)) ? false : true;
                                }
                                if (a == 0) {
                                    imageKey3 = key;
                                    imageUrl = url;
                                } else {
                                    mediaKey = key;
                                    mediaUrl = url;
                                }
                                if (object == thumbLocation) {
                                    if (a == 0) {
                                        imageKey3 = null;
                                        imageUrl = null;
                                        imageLocation2 = null;
                                    } else {
                                        mediaKey = null;
                                        mediaLocation = null;
                                        mediaUrl = null;
                                    }
                                }
                                a++;
                                thumbKey5 = thumbKey3;
                            }
                        }
                        a++;
                        thumbKey5 = thumbKey3;
                    }
                    String thumbKey6 = thumbKey5;
                    if (thumbLocation != null) {
                        thumbUrl = null;
                        thumbKey = thumbKey6;
                    } else {
                        ImageLocation strippedLoc = imageReceiver.getStrippedLocation();
                        if (strippedLoc == null) {
                            strippedLoc = mediaLocation != null ? mediaLocation : imageLocation2;
                        }
                        thumbKey = thumbLocation.getKey(parentObject, strippedLoc);
                        if (thumbLocation.path != null) {
                            String thumbUrl2 = thumbKey + "." + getHttpUrlExtension(thumbLocation.path, "jpg");
                            thumbUrl = thumbUrl2;
                        } else if (thumbLocation.photoSize instanceof TLRPC.TL_photoStrippedSize) {
                            String thumbUrl3 = thumbKey + "." + imageKey2;
                            thumbUrl = thumbUrl3;
                        } else if (thumbLocation.location == null) {
                            thumbUrl = null;
                        } else {
                            String thumbUrl4 = thumbKey + "." + imageKey2;
                            thumbUrl = thumbUrl4;
                        }
                    }
                    if (mediaKey == null && mediaFilter != null) {
                        mediaKey2 = mediaKey + "@" + mediaFilter;
                    } else {
                        mediaKey2 = mediaKey;
                    }
                    if (imageKey3 == null && imageFilter != null) {
                        imageKey4 = imageKey3 + "@" + imageFilter;
                    } else {
                        imageKey4 = imageKey3;
                    }
                    if (thumbKey == null && thumbFilter != null) {
                        thumbKey2 = thumbKey + "@" + thumbFilter;
                    } else {
                        thumbKey2 = thumbKey;
                    }
                    if (imageLocation2 == null && imageLocation2.path != null) {
                        createLoadOperationForImageReceiver(imageReceiver, thumbKey2, thumbUrl, imageKey2, thumbLocation, thumbFilter, 0, 1, 1, thumbSet ? 2 : 1, guid);
                        createLoadOperationForImageReceiver(imageReceiver, imageKey4, imageUrl, imageKey2, imageLocation2, imageFilter, imageReceiver.getSize(), 1, 0, 0, guid);
                        return;
                    }
                    ImageLocation imageLocation4 = imageLocation2;
                    String ext2 = imageKey2;
                    if (mediaLocation == null) {
                        int mediaCacheType2 = imageReceiver.getCacheType();
                        if (mediaCacheType2 == 0 && saveImageToCache) {
                            mediaCacheType = 1;
                        } else {
                            mediaCacheType = mediaCacheType2;
                        }
                        int thumbCacheType = mediaCacheType == 0 ? 1 : mediaCacheType;
                        if (!thumbSet) {
                            createLoadOperationForImageReceiver(imageReceiver, thumbKey2, thumbUrl, ext2, thumbLocation, thumbFilter, 0, thumbCacheType, 1, thumbSet ? 2 : 1, guid);
                        }
                        if (!imageSet2) {
                            createLoadOperationForImageReceiver(imageReceiver, imageKey4, imageUrl, ext2, imageLocation4, imageFilter, 0, 1, 0, 0, guid);
                        }
                        createLoadOperationForImageReceiver(imageReceiver, mediaKey2, mediaUrl, ext2, mediaLocation, mediaFilter, imageReceiver.getSize(), mediaCacheType, 3, 0, guid);
                        return;
                    }
                    int imageCacheType2 = imageReceiver.getCacheType();
                    if (imageCacheType2 == 0 && saveImageToCache) {
                        imageCacheType = 1;
                    } else {
                        imageCacheType = imageCacheType2;
                    }
                    int thumbCacheType2 = imageCacheType == 0 ? 1 : imageCacheType;
                    createLoadOperationForImageReceiver(imageReceiver, thumbKey2, thumbUrl, ext2, thumbLocation, thumbFilter, 0, thumbCacheType2, 1, thumbSet ? 2 : 1, guid);
                    createLoadOperationForImageReceiver(imageReceiver, imageKey4, imageUrl, ext2, imageLocation4, imageFilter, imageReceiver.getSize(), imageCacheType, 0, 0, guid);
                    return;
                }
                qualityThumb = false;
                String thumbKey52 = null;
                ext = imageReceiver.getExt();
                if (ext != null) {
                }
                boolean saveImageToCache2 = false;
                mediaLocation = mediaLocation3;
                String imageUrl2 = null;
                mediaKey = null;
                String mediaUrl2 = null;
                imageKey3 = imageKey;
                imageLocation2 = imageLocation;
                a = 0;
                while (a < 2) {
                }
                String thumbKey62 = thumbKey52;
                if (thumbLocation != null) {
                }
                if (mediaKey == null) {
                }
                mediaKey2 = mediaKey;
                if (imageKey3 == null) {
                }
                imageKey4 = imageKey3;
                if (thumbKey == null) {
                }
                thumbKey2 = thumbKey;
                if (imageLocation2 == null) {
                }
                ImageLocation imageLocation42 = imageLocation2;
                String ext22 = imageKey2;
                if (mediaLocation == null) {
                }
            }
        }
        thumbSet = false;
        parentObject = imageReceiver.getParentObject();
        TLRPC.Document qualityDocument2 = imageReceiver.getQulityThumbDocument();
        thumbLocation = imageReceiver.getThumbLocation();
        String thumbFilter2 = imageReceiver.getThumbFilter();
        ImageLocation mediaLocation32 = imageReceiver.getMediaLocation();
        String mediaFilter2 = imageReceiver.getMediaFilter();
        imageLocation = imageReceiver.getImageLocation();
        String imageFilter2 = imageReceiver.getImageFilter();
        if (imageLocation == null) {
            if (!(parentObject instanceof MessageObject)) {
            }
            String thumbKey522 = null;
            ext = imageReceiver.getExt();
            if (ext != null) {
            }
            boolean saveImageToCache22 = false;
            mediaLocation = mediaLocation32;
            String imageUrl22 = null;
            mediaKey = null;
            String mediaUrl22 = null;
            imageKey3 = imageKey;
            imageLocation2 = imageLocation;
            a = 0;
            while (a < 2) {
            }
            String thumbKey622 = thumbKey522;
            if (thumbLocation != null) {
            }
            if (mediaKey == null) {
            }
            mediaKey2 = mediaKey;
            if (imageKey3 == null) {
            }
            imageKey4 = imageKey3;
            if (thumbKey == null) {
            }
            thumbKey2 = thumbKey;
            if (imageLocation2 == null) {
            }
            ImageLocation imageLocation422 = imageLocation2;
            String ext222 = imageKey2;
            if (mediaLocation == null) {
            }
        }
        qualityThumb = false;
        String thumbKey5222 = null;
        ext = imageReceiver.getExt();
        if (ext != null) {
        }
        boolean saveImageToCache222 = false;
        mediaLocation = mediaLocation32;
        String imageUrl222 = null;
        mediaKey = null;
        String mediaUrl222 = null;
        imageKey3 = imageKey;
        imageLocation2 = imageLocation;
        a = 0;
        while (a < 2) {
        }
        String thumbKey6222 = thumbKey5222;
        if (thumbLocation != null) {
        }
        if (mediaKey == null) {
        }
        mediaKey2 = mediaKey;
        if (imageKey3 == null) {
        }
        imageKey4 = imageKey3;
        if (thumbKey == null) {
        }
        thumbKey2 = thumbKey;
        if (imageLocation2 == null) {
        }
        ImageLocation imageLocation4222 = imageLocation2;
        String ext2222 = imageKey2;
        if (mediaLocation == null) {
        }
    }

    public void httpFileLoadError(final String location) {
        this.imageLoadQueue.postRunnable(new Runnable() {
            @Override
            public final void run() {
                ImageLoader.this.m248lambda$httpFileLoadError$6$imczepdgxadmmessengerImageLoader(location);
            }
        });
    }

    public void m248lambda$httpFileLoadError$6$imczepdgxadmmessengerImageLoader(String location) {
        CacheImage img = this.imageLoadingByUrl.get(location);
        if (img == null) {
            return;
        }
        HttpImageTask oldTask = img.httpTask;
        img.httpTask = new HttpImageTask(oldTask.cacheImage, oldTask.imageSize);
        this.httpTasks.add(img.httpTask);
        runHttpTasks(false);
    }

    public void artworkLoadError(final String location) {
        this.imageLoadQueue.postRunnable(new Runnable() {
            @Override
            public final void run() {
                ImageLoader.this.m241lambda$artworkLoadError$7$imczepdgxadmmessengerImageLoader(location);
            }
        });
    }

    public void m241lambda$artworkLoadError$7$imczepdgxadmmessengerImageLoader(String location) {
        CacheImage img = this.imageLoadingByUrl.get(location);
        if (img == null) {
            return;
        }
        ArtworkLoadTask oldTask = img.artworkTask;
        img.artworkTask = new ArtworkLoadTask(oldTask.cacheImage);
        this.artworkTasks.add(img.artworkTask);
        runArtworkTasks(false);
    }

    public void fileDidLoaded(final String location, final File finalFile, final int type) {
        this.imageLoadQueue.postRunnable(new Runnable() {
            @Override
            public final void run() {
                ImageLoader.this.m247lambda$fileDidLoaded$8$imczepdgxadmmessengerImageLoader(location, type, finalFile);
            }
        });
    }

    public void m247lambda$fileDidLoaded$8$imczepdgxadmmessengerImageLoader(String location, int type, File finalFile) {
        ThumbGenerateInfo info = this.waitingForQualityThumb.get(location);
        if (info != null && info.parentDocument != null) {
            generateThumb(type, finalFile, info);
            this.waitingForQualityThumb.remove(location);
        }
        CacheImage img = this.imageLoadingByUrl.get(location);
        if (img == null) {
            return;
        }
        this.imageLoadingByUrl.remove(location);
        ArrayList<CacheOutTask> tasks = new ArrayList<>();
        for (int a = 0; a < img.imageReceiverArray.size(); a++) {
            String key = img.keys.get(a);
            String filter = img.filters.get(a);
            int imageType = img.imageTypes.get(a).intValue();
            ImageReceiver imageReceiver = img.imageReceiverArray.get(a);
            int guid = img.imageReceiverGuidsArray.get(a).intValue();
            CacheImage cacheImage = this.imageLoadingByKeys.get(key);
            if (cacheImage == null) {
                cacheImage = new CacheImage();
                cacheImage.secureDocument = img.secureDocument;
                cacheImage.currentAccount = img.currentAccount;
                cacheImage.finalFilePath = finalFile;
                cacheImage.key = key;
                cacheImage.imageLocation = img.imageLocation;
                cacheImage.imageType = imageType;
                cacheImage.ext = img.ext;
                cacheImage.encryptionKeyPath = img.encryptionKeyPath;
                cacheImage.cacheTask = new CacheOutTask(cacheImage);
                cacheImage.filter = filter;
                cacheImage.animatedFile = img.animatedFile;
                cacheImage.lottieFile = img.lottieFile;
                this.imageLoadingByKeys.put(key, cacheImage);
                tasks.add(cacheImage.cacheTask);
            }
            cacheImage.addImageReceiver(imageReceiver, key, filter, imageType, guid);
        }
        for (int a2 = 0; a2 < tasks.size(); a2++) {
            CacheOutTask task = tasks.get(a2);
            if (task.cacheImage.imageType == 1) {
                this.cacheThumbOutQueue.postRunnable(task);
            } else {
                this.cacheOutQueue.postRunnable(task);
            }
        }
    }

    public void fileDidFailedLoad(final String location, int canceled) {
        if (canceled == 1) {
            return;
        }
        this.imageLoadQueue.postRunnable(new Runnable() {
            @Override
            public final void run() {
                ImageLoader.this.m246lambda$fileDidFailedLoad$9$imczepdgxadmmessengerImageLoader(location);
            }
        });
    }

    public void m246lambda$fileDidFailedLoad$9$imczepdgxadmmessengerImageLoader(String location) {
        CacheImage img = this.imageLoadingByUrl.get(location);
        if (img != null) {
            img.setImageAndClear(null, null);
        }
    }

    public void runHttpTasks(boolean complete) {
        if (complete) {
            this.currentHttpTasksCount--;
        }
        while (this.currentHttpTasksCount < 4 && !this.httpTasks.isEmpty()) {
            HttpImageTask task = this.httpTasks.poll();
            if (task != null) {
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
                this.currentHttpTasksCount++;
            }
        }
    }

    public void runArtworkTasks(boolean complete) {
        if (complete) {
            this.currentArtworkTasksCount--;
        }
        while (this.currentArtworkTasksCount < 4 && !this.artworkTasks.isEmpty()) {
            try {
                ArtworkLoadTask task = this.artworkTasks.poll();
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
                this.currentArtworkTasksCount++;
            } catch (Throwable th) {
                runArtworkTasks(false);
            }
        }
    }

    public boolean isLoadingHttpFile(String url) {
        return this.httpFileLoadTasksByKeys.containsKey(url);
    }

    public static String getHttpFileName(String url) {
        return Utilities.MD5(url);
    }

    public static File getHttpFilePath(String url, String defaultExt) {
        String ext = getHttpUrlExtension(url, defaultExt);
        return new File(FileLoader.getDirectory(4), Utilities.MD5(url) + "." + ext);
    }

    public void loadHttpFile(String url, String defaultExt, int currentAccount) {
        if (url == null || url.length() == 0 || this.httpFileLoadTasksByKeys.containsKey(url)) {
            return;
        }
        String ext = getHttpUrlExtension(url, defaultExt);
        File file = new File(FileLoader.getDirectory(4), Utilities.MD5(url) + "_temp." + ext);
        file.delete();
        HttpFileTask task = new HttpFileTask(url, file, ext, currentAccount);
        this.httpFileLoadTasks.add(task);
        this.httpFileLoadTasksByKeys.put(url, task);
        runHttpFileLoadTasks(null, 0);
    }

    public void cancelLoadHttpFile(String url) {
        HttpFileTask task = this.httpFileLoadTasksByKeys.get(url);
        if (task != null) {
            task.cancel(true);
            this.httpFileLoadTasksByKeys.remove(url);
            this.httpFileLoadTasks.remove(task);
        }
        Runnable runnable = this.retryHttpsTasks.get(url);
        if (runnable != null) {
            AndroidUtilities.cancelRunOnUIThread(runnable);
        }
        runHttpFileLoadTasks(null, 0);
    }

    public void runHttpFileLoadTasks(final HttpFileTask oldTask, final int reason) {
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public final void run() {
                ImageLoader.this.m251x290f37b1(oldTask, reason);
            }
        });
    }

    public void m251x290f37b1(HttpFileTask oldTask, int reason) {
        if (oldTask != null) {
            this.currentHttpFileLoadTasksCount--;
        }
        if (oldTask != null) {
            if (reason == 1) {
                if (!oldTask.canRetry) {
                    this.httpFileLoadTasksByKeys.remove(oldTask.url);
                    NotificationCenter.getInstance(oldTask.currentAccount).postNotificationName(NotificationCenter.httpFileDidFailedLoad, oldTask.url, 0);
                } else {
                    final HttpFileTask newTask = new HttpFileTask(oldTask.url, oldTask.tempFile, oldTask.ext, oldTask.currentAccount);
                    Runnable runnable = new Runnable() {
                        @Override
                        public final void run() {
                            ImageLoader.this.m250x15676430(newTask);
                        }
                    };
                    this.retryHttpsTasks.put(oldTask.url, runnable);
                    AndroidUtilities.runOnUIThread(runnable, 1000L);
                }
            } else if (reason == 2) {
                this.httpFileLoadTasksByKeys.remove(oldTask.url);
                File file = new File(FileLoader.getDirectory(4), Utilities.MD5(oldTask.url) + "." + oldTask.ext);
                String result = oldTask.tempFile.renameTo(file) ? file.toString() : oldTask.tempFile.toString();
                NotificationCenter.getInstance(oldTask.currentAccount).postNotificationName(NotificationCenter.httpFileDidLoad, oldTask.url, result);
            }
        }
        while (this.currentHttpFileLoadTasksCount < 2 && !this.httpFileLoadTasks.isEmpty()) {
            HttpFileTask task = this.httpFileLoadTasks.poll();
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
            this.currentHttpFileLoadTasksCount++;
        }
    }

    public void m250x15676430(HttpFileTask newTask) {
        this.httpFileLoadTasks.add(newTask);
        runHttpFileLoadTasks(null, 0);
    }

    public static boolean shouldSendImageAsDocument(String path, Uri uri) {
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        if (path == null && uri != null && uri.getScheme() != null) {
            if (uri.getScheme().contains("file")) {
                path = uri.getPath();
            } else {
                try {
                    path = AndroidUtilities.getPath(uri);
                } catch (Throwable e) {
                    FileLog.e(e);
                }
            }
        }
        if (path != null) {
            BitmapFactory.decodeFile(path, bmOptions);
        } else if (uri != null) {
            try {
                InputStream inputStream = ApplicationLoader.applicationContext.getContentResolver().openInputStream(uri);
                BitmapFactory.decodeStream(inputStream, null, bmOptions);
                inputStream.close();
            } catch (Throwable e2) {
                FileLog.e(e2);
                return false;
            }
        }
        float photoW = bmOptions.outWidth;
        float photoH = bmOptions.outHeight;
        return photoW / photoH > 10.0f || photoH / photoW > 10.0f;
    }

    public static Bitmap loadBitmap(String path, Uri uri, float maxWidth, float maxHeight, boolean useMaxScale) {
        String imageFilePath;
        float scaleFactor;
        float scaleFactor2;
        String exifPath;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        InputStream inputStream = null;
        if (path == null && uri != null && uri.getScheme() != null) {
            if (uri.getScheme().contains("file")) {
                imageFilePath = uri.getPath();
            } else {
                try {
                    imageFilePath = AndroidUtilities.getPath(uri);
                } catch (Throwable e) {
                    FileLog.e(e);
                }
            }
            if (imageFilePath == null) {
                BitmapFactory.decodeFile(imageFilePath, bmOptions);
            } else if (uri != null) {
                try {
                    InputStream inputStream2 = ApplicationLoader.applicationContext.getContentResolver().openInputStream(uri);
                    BitmapFactory.decodeStream(inputStream2, null, bmOptions);
                    inputStream2.close();
                    inputStream = ApplicationLoader.applicationContext.getContentResolver().openInputStream(uri);
                } catch (Throwable e2) {
                    FileLog.e(e2);
                    return null;
                }
            }
            float photoW = bmOptions.outWidth;
            float photoH = bmOptions.outHeight;
            float f = photoW / maxWidth;
            float f2 = photoH / maxHeight;
            scaleFactor = !useMaxScale ? Math.max(f, f2) : Math.min(f, f2);
            if (scaleFactor < 1.0f) {
                scaleFactor2 = scaleFactor;
            } else {
                scaleFactor2 = 1.0f;
            }
            bmOptions.inJustDecodeBounds = false;
            bmOptions.inSampleSize = (int) scaleFactor2;
            if (bmOptions.inSampleSize % 2 != 0) {
                int sample = 1;
                while (sample * 2 < bmOptions.inSampleSize) {
                    sample *= 2;
                }
                bmOptions.inSampleSize = sample;
            }
            bmOptions.inPurgeable = false;
            if (imageFilePath == null) {
                String exifPath2 = imageFilePath;
                exifPath = exifPath2;
            } else if (uri == null) {
                exifPath = null;
            } else {
                String exifPath3 = AndroidUtilities.getPath(uri);
                exifPath = exifPath3;
            }
            Matrix matrix = null;
            if (exifPath != null) {
                try {
                    ExifInterface exif = new ExifInterface(exifPath);
                    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
                    matrix = new Matrix();
                    switch (orientation) {
                        case 3:
                            matrix.postRotate(180.0f);
                            break;
                        case 6:
                            matrix.postRotate(90.0f);
                            break;
                        case 8:
                            matrix.postRotate(270.0f);
                            break;
                    }
                } catch (Throwable th) {
                }
            }
            Bitmap b = null;
            if (imageFilePath == null) {
                try {
                    b = BitmapFactory.decodeFile(imageFilePath, bmOptions);
                    if (b != null) {
                        if (bmOptions.inPurgeable) {
                            Utilities.pinBitmap(b);
                        }
                        Bitmap newBitmap = Bitmaps.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
                        if (newBitmap != b) {
                            b.recycle();
                            return newBitmap;
                        }
                        return b;
                    }
                    return b;
                } catch (Throwable e3) {
                    FileLog.e(e3);
                    getInstance().clearMemory();
                    if (b == null) {
                        try {
                            b = BitmapFactory.decodeFile(imageFilePath, bmOptions);
                            if (b != null && bmOptions.inPurgeable) {
                                Utilities.pinBitmap(b);
                            }
                        } catch (Throwable e22) {
                            FileLog.e(e22);
                            return b;
                        }
                    }
                    if (b != null) {
                        Bitmap newBitmap2 = Bitmaps.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
                        if (newBitmap2 != b) {
                            b.recycle();
                            return newBitmap2;
                        }
                        return b;
                    }
                    return b;
                }
            }
            try {
                if (uri == null) {
                    return null;
                }
                try {
                    b = BitmapFactory.decodeStream(inputStream, null, bmOptions);
                    if (b != null) {
                        if (bmOptions.inPurgeable) {
                            Utilities.pinBitmap(b);
                        }
                        Bitmap newBitmap3 = Bitmaps.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
                        if (newBitmap3 != b) {
                            b.recycle();
                            b = newBitmap3;
                        }
                    }
                    inputStream.close();
                    return b;
                } catch (Throwable e4) {
                    try {
                        FileLog.e(e4);
                        inputStream.close();
                        return b;
                    } finally {
                    }
                }
            } catch (Throwable e5) {
                FileLog.e(e5);
                return b;
            }
        }
        imageFilePath = path;
        if (imageFilePath == null) {
        }
        float photoW2 = bmOptions.outWidth;
        float photoH2 = bmOptions.outHeight;
        float f3 = photoW2 / maxWidth;
        float f22 = photoH2 / maxHeight;
        if (!useMaxScale) {
        }
        if (scaleFactor < 1.0f) {
        }
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = (int) scaleFactor2;
        if (bmOptions.inSampleSize % 2 != 0) {
        }
        bmOptions.inPurgeable = false;
        if (imageFilePath == null) {
        }
        Matrix matrix2 = null;
        if (exifPath != null) {
        }
        Bitmap b2 = null;
        if (imageFilePath == null) {
        }
    }

    public static void fillPhotoSizeWithBytes(TLRPC.PhotoSize photoSize) {
        if (photoSize != null) {
            if (photoSize.bytes != null && photoSize.bytes.length != 0) {
                return;
            }
            File file = FileLoader.getPathToAttach(photoSize, true);
            try {
                RandomAccessFile f = new RandomAccessFile(file, "r");
                int len = (int) f.length();
                if (len < 20000) {
                    photoSize.bytes = new byte[(int) f.length()];
                    f.readFully(photoSize.bytes, 0, photoSize.bytes.length);
                }
            } catch (Throwable e) {
                FileLog.e(e);
            }
        }
    }

    private static TLRPC.PhotoSize scaleAndSaveImageInternal(TLRPC.PhotoSize photoSize, Bitmap bitmap, int w, int h, float photoW, float photoH, float scaleFactor, int quality, boolean cache, boolean scaleAnyway, boolean isPng) throws Exception {
        Bitmap scaledBitmap;
        TLRPC.TL_fileLocationToBeDeprecated location;
        TLRPC.PhotoSize photoSize2 = photoSize;
        if (scaleFactor > 1.0f || scaleAnyway) {
            scaledBitmap = Bitmaps.createScaledBitmap(bitmap, w, h, true);
        } else {
            scaledBitmap = bitmap;
        }
        if (photoSize2 == null) {
        }
        if (photoSize2 == null || !(photoSize2.location instanceof TLRPC.TL_fileLocationToBeDeprecated)) {
            location = new TLRPC.TL_fileLocationToBeDeprecated();
            location.volume_id = -2147483648L;
            location.dc_id = Integer.MIN_VALUE;
            location.local_id = SharedConfig.getLastLocalId();
            location.file_reference = new byte[0];
            photoSize2 = new TLRPC.TL_photoSize();
            photoSize2.location = location;
            photoSize2.w = scaledBitmap.getWidth();
            photoSize2.h = scaledBitmap.getHeight();
            if (photoSize2.w <= 100 && photoSize2.h <= 100) {
                photoSize2.type = "s";
            } else if (photoSize2.w <= 320 && photoSize2.h <= 320) {
                photoSize2.type = "m";
            } else if (photoSize2.w <= 800 && photoSize2.h <= 800) {
                photoSize2.type = "x";
            } else if (photoSize2.w <= 1280 && photoSize2.h <= 1280) {
                photoSize2.type = "y";
            } else {
                photoSize2.type = "w";
            }
        } else {
            location = (TLRPC.TL_fileLocationToBeDeprecated) photoSize2.location;
        }
        String fileName = location.volume_id + "_" + location.local_id + ".jpg";
        File cacheFile = new File(FileLoader.getDirectory(location.volume_id == -2147483648L ? 4 : 0), fileName);
        FileOutputStream stream = new FileOutputStream(cacheFile);
        if (isPng) {
            scaledBitmap.compress(Bitmap.CompressFormat.PNG, quality, stream);
        } else {
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
        }
        if (cache) {
            ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
            if (isPng) {
                scaledBitmap.compress(Bitmap.CompressFormat.PNG, quality, stream2);
            } else {
                scaledBitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream2);
            }
            photoSize2.bytes = stream2.toByteArray();
            photoSize2.size = photoSize2.bytes.length;
            stream2.close();
        } else {
            photoSize2.size = (int) stream.getChannel().size();
        }
        stream.close();
        if (scaledBitmap != bitmap) {
            scaledBitmap.recycle();
        }
        return photoSize2;
    }

    public static TLRPC.PhotoSize SaveImageWithOriginalInternal(TLRPC.PhotoSize photoSize, String strPath, boolean cache) throws Exception {
        TLRPC.TL_fileLocationToBeDeprecated location;
        if (photoSize != null) {
        }
        if (photoSize == null || !(photoSize.location instanceof TLRPC.TL_fileLocationToBeDeprecated)) {
            location = new TLRPC.TL_fileLocationToBeDeprecated();
            location.volume_id = -2147483648L;
            location.dc_id = Integer.MIN_VALUE;
            location.local_id = SharedConfig.getLastLocalId();
            location.file_reference = new byte[0];
            photoSize = new TLRPC.TL_photoSize();
            photoSize.location = location;
            BitmapFactory.Options options = new BitmapFactory.Options();
            BitmapFactory.decodeFile(strPath, options);
            photoSize.w = options.outWidth;
            photoSize.h = options.outHeight;
            if (photoSize.w <= 100 && photoSize.h <= 100) {
                photoSize.type = "s";
            } else if (photoSize.w <= 320 && photoSize.h <= 320) {
                photoSize.type = "m";
            } else if (photoSize.w <= 800 && photoSize.h <= 800) {
                photoSize.type = "x";
            } else if (photoSize.w <= 1280 && photoSize.h <= 1280) {
                photoSize.type = "y";
            } else {
                photoSize.type = "w";
            }
        } else {
            location = (TLRPC.TL_fileLocationToBeDeprecated) photoSize.location;
        }
        String fileName = location.volume_id + "_" + location.local_id + ".jpg";
        File cacheFile = new File(FileLoader.getDirectory(location.volume_id == -2147483648L ? 4 : 0), fileName);
        FileInputStream fileInputStream = new FileInputStream(strPath);
        AndroidUtilities.copyFile(fileInputStream, cacheFile);
        if (cache) {
            ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
            photoSize.bytes = stream2.toByteArray();
            photoSize.size = photoSize.bytes.length;
            stream2.close();
        } else {
            photoSize.size = (int) fileInputStream.getChannel().size();
        }
        fileInputStream.close();
        return photoSize;
    }

    public static TLRPC.PhotoSize scaleAndSaveImage(Bitmap bitmap, float maxWidth, float maxHeight, int quality, boolean cache) {
        return scaleAndSaveImage(null, bitmap, maxWidth, maxHeight, quality, cache, 0, 0, false);
    }

    public static TLRPC.PhotoSize scaleAndSaveImage(TLRPC.PhotoSize photoSize, Bitmap bitmap, float maxWidth, float maxHeight, int quality, boolean cache) {
        return scaleAndSaveImage(photoSize, bitmap, maxWidth, maxHeight, quality, cache, 0, 0, false);
    }

    public static TLRPC.PhotoSize scaleAndSaveImage(Bitmap bitmap, float maxWidth, float maxHeight, int quality, boolean cache, int minWidth, int minHeight) {
        return scaleAndSaveImage(null, bitmap, maxWidth, maxHeight, quality, cache, minWidth, minHeight, false);
    }

    public static TLRPC.PhotoSize scaleAndSaveImage(Bitmap bitmap, float maxWidth, float maxHeight, int quality, boolean cache, boolean isPng) {
        return scaleAndSaveImage(null, bitmap, maxWidth, maxHeight, quality, cache, 0, 0, isPng);
    }

    public static TLRPC.PhotoSize scaleAndSaveImage(Bitmap bitmap, float maxWidth, float maxHeight, int quality, boolean cache, int minWidth, int minHeight, boolean isPng) {
        return scaleAndSaveImage(null, bitmap, maxWidth, maxHeight, quality, cache, minWidth, minHeight, isPng);
    }

    public static TLRPC.PhotoSize scaleAndSaveImage(TLRPC.PhotoSize photoSize, Bitmap bitmap, float maxWidth, float maxHeight, int quality, boolean cache, int minWidth, int minHeight, boolean isPng) {
        boolean scaleAnyway;
        float scaleFactor;
        float scaleFactor2;
        if (bitmap == null) {
            return null;
        }
        float photoW = bitmap.getWidth();
        float photoH = bitmap.getHeight();
        if (photoW != 0.0f && photoH != 0.0f) {
            float scaleFactor3 = Math.max(photoW / maxWidth, photoH / maxHeight);
            if (minWidth != 0 && minHeight != 0 && (photoW < minWidth || photoH < minHeight)) {
                if (photoW < minWidth && photoH > minHeight) {
                    scaleFactor2 = photoW / minWidth;
                } else if (photoW > minWidth && photoH < minHeight) {
                    scaleFactor2 = photoH / minHeight;
                } else {
                    scaleFactor2 = Math.max(photoW / minWidth, photoH / minHeight);
                }
                scaleAnyway = true;
                scaleFactor = scaleFactor2;
            } else {
                scaleAnyway = false;
                scaleFactor = scaleFactor3;
            }
            int w = (int) (photoW / scaleFactor);
            int h = (int) (photoH / scaleFactor);
            if (h != 0 && w != 0) {
                try {
                    return scaleAndSaveImageInternal(photoSize, bitmap, w, h, photoW, photoH, scaleFactor, quality, cache, scaleAnyway, isPng);
                } catch (Throwable e) {
                    FileLog.e(e);
                    getInstance().clearMemory();
                    System.gc();
                    try {
                        return scaleAndSaveImageInternal(photoSize, bitmap, w, h, photoW, photoH, scaleFactor, quality, cache, scaleAnyway, isPng);
                    } catch (Throwable e2) {
                        FileLog.e(e2);
                        return null;
                    }
                }
            }
            return null;
        }
        return null;
    }

    public static String getHttpUrlExtension(String url, String defaultExt) {
        String ext = null;
        String last = Uri.parse(url).getLastPathSegment();
        if (!TextUtils.isEmpty(last) && last.length() > 1) {
            url = last;
        }
        int idx = url.lastIndexOf(46);
        if (idx != -1) {
            ext = url.substring(idx + 1);
        }
        if (ext == null || ext.length() == 0 || ext.length() > 4) {
            return defaultExt;
        }
        return ext;
    }

    public static void saveMessageThumbs(TLRPC.Message message) {
        TLRPC.PhotoSize photoSize;
        boolean isEncrypted;
        File file;
        TLRPC.PhotoSize photoSize2 = null;
        if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
            int a = 0;
            int count = message.media.photo.sizes.size();
            while (true) {
                if (a >= count) {
                    break;
                }
                TLRPC.PhotoSize size = message.media.photo.sizes.get(a);
                if (!(size instanceof TLRPC.TL_photoCachedSize)) {
                    a++;
                } else {
                    photoSize2 = size;
                    break;
                }
            }
            photoSize = photoSize2;
        } else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
            int a2 = 0;
            int count2 = message.media.document.thumbs.size();
            while (true) {
                if (a2 >= count2) {
                    break;
                }
                TLRPC.PhotoSize size2 = message.media.document.thumbs.get(a2);
                if (!(size2 instanceof TLRPC.TL_photoCachedSize)) {
                    a2++;
                } else {
                    photoSize2 = size2;
                    break;
                }
            }
            photoSize = photoSize2;
        } else {
            if ((message.media instanceof TLRPC.TL_messageMediaWebPage) && message.media.webpage.photo != null) {
                int count3 = message.media.webpage.photo.sizes.size();
                for (int a3 = 0; a3 < count3; a3++) {
                    TLRPC.PhotoSize size3 = message.media.webpage.photo.sizes.get(a3);
                    if (size3 instanceof TLRPC.TL_photoCachedSize) {
                        photoSize = size3;
                        break;
                    }
                }
            }
            photoSize = null;
        }
        if (photoSize != null && photoSize.bytes != null && photoSize.bytes.length != 0) {
            if (photoSize.location == null || (photoSize.location instanceof TLRPC.TL_fileLocationUnavailable)) {
                photoSize.location = new TLRPC.TL_fileLocationToBeDeprecated();
                photoSize.location.volume_id = -2147483648L;
                photoSize.location.local_id = SharedConfig.getLastLocalId();
            }
            File file2 = FileLoader.getPathToAttach(photoSize, true);
            if (!MessageObject.shouldEncryptPhotoOrVideo(message)) {
                isEncrypted = false;
                file = file2;
            } else {
                isEncrypted = true;
                file = new File(file2.getAbsolutePath() + ".enc");
            }
            if (!file.exists()) {
                if (isEncrypted) {
                    try {
                        File keyPath = new File(FileLoader.getInternalCacheDir(), file.getName() + ".key");
                        RandomAccessFile keyFile = new RandomAccessFile(keyPath, "rws");
                        long len = keyFile.length();
                        byte[] encryptKey = new byte[32];
                        byte[] encryptIv = new byte[16];
                        if (len > 0 && len % 48 == 0) {
                            keyFile.read(encryptKey, 0, 32);
                            keyFile.read(encryptIv, 0, 16);
                        } else {
                            Utilities.random.nextBytes(encryptKey);
                            Utilities.random.nextBytes(encryptIv);
                            keyFile.write(encryptKey);
                            keyFile.write(encryptIv);
                        }
                        keyFile.close();
                        Utilities.aesCtrDecryptionByteArray(photoSize.bytes, encryptKey, encryptIv, 0, photoSize.bytes.length, 0);
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
                RandomAccessFile writeFile = new RandomAccessFile(file, "rws");
                writeFile.write(photoSize.bytes);
                writeFile.close();
            }
            TLRPC.TL_photoSize newPhotoSize = new TLRPC.TL_photoSize();
            newPhotoSize.w = photoSize.w;
            newPhotoSize.h = photoSize.h;
            newPhotoSize.location = photoSize.location;
            newPhotoSize.size = photoSize.size;
            newPhotoSize.type = photoSize.type;
            if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
                int count4 = message.media.photo.sizes.size();
                for (int a4 = 0; a4 < count4; a4++) {
                    if (message.media.photo.sizes.get(a4) instanceof TLRPC.TL_photoCachedSize) {
                        message.media.photo.sizes.set(a4, newPhotoSize);
                        return;
                    }
                }
                return;
            }
            if (message.media instanceof TLRPC.TL_messageMediaDocument) {
                int count5 = message.media.document.thumbs.size();
                for (int a5 = 0; a5 < count5; a5++) {
                    if (message.media.document.thumbs.get(a5) instanceof TLRPC.TL_photoCachedSize) {
                        message.media.document.thumbs.set(a5, newPhotoSize);
                        return;
                    }
                }
                return;
            }
            if (message.media instanceof TLRPC.TL_messageMediaWebPage) {
                int count6 = message.media.webpage.photo.sizes.size();
                for (int a6 = 0; a6 < count6; a6++) {
                    if (message.media.webpage.photo.sizes.get(a6) instanceof TLRPC.TL_photoCachedSize) {
                        message.media.webpage.photo.sizes.set(a6, newPhotoSize);
                        return;
                    }
                }
            }
        }
    }

    public static void saveMessagesThumbs(ArrayList<TLRPC.Message> messages) {
        if (messages == null || messages.isEmpty()) {
            return;
        }
        for (int a = 0; a < messages.size(); a++) {
            TLRPC.Message message = messages.get(a);
            saveMessageThumbs(message);
        }
    }
}