青竹传媒 v1.0.0版本的 MD5 值为:d5ec664fe20c17fd4f187bc728262336

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


package im.jpeoubogmn.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.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.SparseArray;
import androidx.exifinterface.media.ExifInterface;
import androidx.recyclerview.widget.ItemTouchHelper;
import com.google.android.exoplayer2.util.MimeTypes;
import com.king.zxing.util.LogUtils;
import im.jpeoubogmn.messenger.FileLoader;
import im.jpeoubogmn.messenger.ImageLoader;
import im.jpeoubogmn.messenger.secretmedia.EncryptedFileInputStream;
import im.jpeoubogmn.tgnet.ConnectionsManager;
import im.jpeoubogmn.tgnet.RequestDelegate;
import im.jpeoubogmn.tgnet.TLObject;
import im.jpeoubogmn.tgnet.TLRPC;
import im.jpeoubogmn.ui.components.AnimatedFileDrawable;
import im.jpeoubogmn.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.ByteBuffer;
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.lambda$reportProgress$1$ImageLoader$HttpFileTask(progress);
                }
            });
        }

        public void lambda$reportProgress$1$ImageLoader$HttpFileTask(final float progress) {
            ImageLoader.this.fileProgresses.put(this.url, Float.valueOf(progress));
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpFileTask.this.lambda$null$0$ImageLoader$HttpFileTask(progress);
                }
            });
        }

        public void lambda$null$0$ImageLoader$HttpFileTask(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;
                                    if (this.fileSize > 0) {
                                        reportProgress(totalLoaded / this.fileSize);
                                    }
                                } 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 {
                    if (this.fileOutputStream != null) {
                        this.fileOutputStream.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 code;
            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 {
                    if (this.httpConnection != null && (code = this.httpConnection.getResponseCode()) != 200 && code != 202 && code != 304) {
                        this.canRetry = false;
                    }
                } catch (Exception e) {
                    FileLog.e(e);
                }
                InputStream httpConnectionStream = this.httpConnection.getInputStream();
                ByteArrayOutputStream outbuf = new ByteArrayOutputStream();
                byte[] data = new byte[32768];
                while (true) {
                    if (isCancelled()) {
                        break;
                    }
                    int read = httpConnectionStream.read(data);
                    if (read > 0) {
                        outbuf.write(data, 0, read);
                    } else if (read == -1) {
                    }
                }
                this.canRetry = false;
                JSONObject object = new JSONObject(new String(outbuf.toByteArray()));
                JSONArray array = object.getJSONArray("results");
                if (array.length() <= 0) {
                    try {
                        if (this.httpConnection != null) {
                            this.httpConnection.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 {
                        if (this.httpConnection != null) {
                            this.httpConnection.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 {
                    if (this.httpConnection != null) {
                        this.httpConnection.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;
            }
        }

        @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.lambda$onPostExecute$0$ImageLoader$ArtworkLoadTask();
                }
            });
        }

        public void lambda$onPostExecute$0$ImageLoader$ArtworkLoadTask() {
            ImageLoader.this.runArtworkTasks(true);
        }

        public void lambda$onCancelled$1$ImageLoader$ArtworkLoadTask() {
            ImageLoader.this.runArtworkTasks(true);
        }

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

    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.lambda$reportProgress$1$ImageLoader$HttpImageTask(progress);
                }
            });
        }

        public void lambda$reportProgress$1$ImageLoader$HttpImageTask(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.lambda$null$0$ImageLoader$HttpImageTask(progress);
                }
            });
        }

        public void lambda$null$0$ImageLoader$HttpImageTask(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);
                            }
                        });
                    }
                    URL downloadUrl = new URL(this.overrideUrl != null ? this.overrideUrl : location);
                    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 {
                    if (this.httpConnection != null && (code = this.httpConnection.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);
                                    if (this.imageSize != 0) {
                                        reportProgress(totalLoaded / this.imageSize);
                                    }
                                } 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 {
                if (this.fileOutputStream != null) {
                    this.fileOutputStream.close();
                    this.fileOutputStream = null;
                }
            } catch (Throwable e6) {
                FileLog.e(e6);
            }
            try {
                if (this.httpConnection != null) {
                    this.httpConnection.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.lambda$onPostExecute$4$ImageLoader$HttpImageTask(result);
                }
            });
            ImageLoader.this.imageLoadQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.lambda$onPostExecute$5$ImageLoader$HttpImageTask();
                }
            });
        }

        public void lambda$onPostExecute$4$ImageLoader$HttpImageTask(final Boolean result) {
            ImageLoader.this.fileProgresses.remove(this.cacheImage.url);
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.lambda$null$3$ImageLoader$HttpImageTask(result);
                }
            });
        }

        public void lambda$null$3$ImageLoader$HttpImageTask(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 lambda$onPostExecute$5$ImageLoader$HttpImageTask() {
            ImageLoader.this.runHttpTasks(true);
        }

        public void lambda$onCancelled$6$ImageLoader$HttpImageTask() {
            ImageLoader.this.runHttpTasks(true);
        }

        @Override
        protected void onCancelled() {
            ImageLoader.this.imageLoadQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.lambda$onCancelled$6$ImageLoader$HttpImageTask();
                }
            });
            Utilities.stageQueue.postRunnable(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.lambda$onCancelled$8$ImageLoader$HttpImageTask();
                }
            });
        }

        public void lambda$onCancelled$8$ImageLoader$HttpImageTask() {
            ImageLoader.this.fileProgresses.remove(this.cacheImage.url);
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    ImageLoader.HttpImageTask.this.lambda$null$7$ImageLoader$HttpImageTask();
                }
            });
        }

        public void lambda$null$7$ImageLoader$HttpImageTask() {
            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.lambda$removeTask$0$ImageLoader$ThumbGenerateTask(name);
                    }
                });
            }
        }

        public void lambda$removeTask$0$ImageLoader$ThumbGenerateTask(String name) {
            ThumbGenerateTask thumbGenerateTask = (ThumbGenerateTask) ImageLoader.this.thumbGenerateTasks.remove(name);
        }

        @Override
        public void run() {
            Bitmap originalBitmap;
            Bitmap scaledBitmap;
            try {
                if (this.info == null) {
                    removeTask();
                    return;
                }
                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;
                    if (this.mediaType == 0) {
                        originalBitmap2 = ImageLoader.loadBitmap(this.originalPath.toString(), null, size, size, false);
                    } else {
                        int i = 2;
                        if (this.mediaType == 2) {
                            String file = this.originalPath.toString();
                            if (!this.info.big) {
                                i = 1;
                            }
                            originalBitmap2 = ThumbnailUtils.createVideoThumbnail(file, i);
                        } else if (this.mediaType == 3) {
                            String path = this.originalPath.toString().toLowerCase();
                            if (path.endsWith("mp4")) {
                                String file2 = this.originalPath.toString();
                                if (!this.info.big) {
                                    i = 1;
                                }
                                originalBitmap2 = ThumbnailUtils.createVideoThumbnail(file2, i);
                            } 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.lambda$run$1$ImageLoader$ThumbGenerateTask(key, finalImageReceiverArray, bitmapDrawable, finalImageReceiverGuidsArray);
                            }
                        });
                        return;
                    }
                    removeTask();
                    return;
                }
                removeTask();
            } catch (Throwable e2) {
                FileLog.e(e2);
                removeTask();
            }
        }

        public void lambda$run$1$ImageLoader$ThumbGenerateTask(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 image;
            File cacheFileFinal;
            byte[] secureDocumentHash;
            SecureDocumentKey secureDocumentKey;
            boolean canDeleteFile;
            String location;
            BitmapFactory.Options opts;
            boolean checkInversion;
            boolean needInvert;
            float h_filter;
            Bitmap bitmap;
            float h_filter2;
            float w_filter;
            boolean needInvert2;
            int orientation;
            float h_filter3;
            boolean inEncryptedFile;
            SecureDocumentKey secureDocumentKey2;
            FileInputStream is;
            boolean blured;
            Bitmap scaledBitmap;
            Bitmap image2;
            FileInputStream is2;
            float scaleFactor;
            AnimatedFileDrawable fileDrawable;
            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 photoSize = (TLRPC.TL_photoStrippedSize) this.cacheImage.imageLocation.photoSize;
                        int len = (photoSize.bytes.length - 3) + Bitmaps.header.length + Bitmaps.footer.length;
                        byte[] bytes = (byte[]) ImageLoader.bytesLocal.get();
                        byte[] data = (bytes == null || bytes.length < len) ? null : bytes;
                        if (data == null) {
                            byte[] bytes2 = new byte[len];
                            data = bytes2;
                            ImageLoader.bytesLocal.set(bytes2);
                        }
                        System.arraycopy(Bitmaps.header, 0, data, 0, Bitmaps.header.length);
                        System.arraycopy(photoSize.bytes, 3, data, Bitmaps.header.length, photoSize.bytes.length - 3);
                        System.arraycopy(Bitmaps.footer, 0, data, (Bitmaps.header.length + photoSize.bytes.length) - 3, Bitmaps.footer.length);
                        data[164] = photoSize.bytes[1];
                        data[166] = photoSize.bytes[2];
                        Bitmap bitmap2 = BitmapFactory.decodeByteArray(data, 0, len);
                        if (bitmap2 != null && !TextUtils.isEmpty(this.cacheImage.filter) && this.cacheImage.filter.contains("b")) {
                            Utilities.blurBitmap(bitmap2, 3, 1, bitmap2.getWidth(), bitmap2.getHeight(), bitmap2.getRowBytes());
                        }
                        onPostExecute(bitmap2 != null ? new BitmapDrawable(bitmap2) : null);
                        return;
                    }
                } else if (this.cacheImage.lottieFile) {
                    synchronized (this.sync) {
                        if (this.isCancelled) {
                            return;
                        }
                        int w = Math.min(512, AndroidUtilities.dp(170.6f));
                        int h = Math.min(512, AndroidUtilities.dp(170.6f));
                        boolean precache = false;
                        boolean limitFps = false;
                        int autoRepeat = 1;
                        int[] colors = null;
                        if (this.cacheImage.filter != null) {
                            String[] args = this.cacheImage.filter.split("_");
                            if (args.length >= 2) {
                                float w_filter2 = Float.parseFloat(args[0]);
                                float h_filter4 = Float.parseFloat(args[1]);
                                w = Math.min(512, (int) (w_filter2 * AndroidUtilities.density));
                                h = Math.min(512, (int) (AndroidUtilities.density * h_filter4));
                                if (w_filter2 <= 90.0f && h_filter4 <= 90.0f) {
                                    w = Math.min(w, 160);
                                    h = Math.min(h, 160);
                                    limitFps = true;
                                    precache = SharedConfig.getDevicePerfomanceClass() != 2;
                                }
                            }
                            if (args.length >= 3) {
                                if ("nr".equals(args[2])) {
                                    autoRepeat = 2;
                                } else if ("nrs".equals(args[2])) {
                                    autoRepeat = 3;
                                }
                            }
                            if (args.length >= 5) {
                                if ("c1".equals(args[4])) {
                                    colors = new int[]{16219713, 13275258, 16757049, 15582629, 16765248, 16245699, 16768889, 16510934};
                                } else if ("c2".equals(args[4])) {
                                    colors = new int[]{16219713, 11172960, 16757049, 13150599, 16765248, 14534815, 16768889, 15128242};
                                } else if ("c3".equals(args[4])) {
                                    colors = new int[]{16219713, 9199944, 16757049, 11371874, 16765248, 12885622, 16768889, 13939080};
                                } else if ("c4".equals(args[4])) {
                                    colors = new int[]{16219713, 7224364, 16757049, 9591348, 16765248, 10579526, 16768889, 11303506};
                                } else if ("c5".equals(args[4])) {
                                    colors = new int[]{16219713, 2694162, 16757049, 4663842, 16765248, 5716784, 16768889, 6834492};
                                }
                            }
                        }
                        RLottieDrawable lottieDrawable = new RLottieDrawable(this.cacheImage.finalFilePath, w, h, precache, limitFps, colors);
                        lottieDrawable.setAutoRepeat(autoRepeat);
                        onPostExecute(lottieDrawable);
                        return;
                    }
                } else 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)) {
                            fileDrawable = new AnimatedFileDrawable(this.cacheImage.finalFilePath, "d".equals(this.cacheImage.filter), 0L, null, null, this.cacheImage.currentAccount, false);
                        } else {
                            fileDrawable = 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(fileDrawable);
                        return;
                    }
                } else {
                    Long mediaId = null;
                    boolean mediaIsVideo = false;
                    image = null;
                    cacheFileFinal = this.cacheImage.finalFilePath;
                    boolean inEncryptedFile2 = (this.cacheImage.secureDocument == null && (this.cacheImage.encryptionKeyPath == null || cacheFileFinal == null || !cacheFileFinal.getAbsolutePath().endsWith(".enc"))) ? false : true;
                    if (this.cacheImage.secureDocument != null) {
                        SecureDocumentKey secureDocumentKey3 = this.cacheImage.secureDocument.secureDocumentKey;
                        if (this.cacheImage.secureDocument.secureFile == null || this.cacheImage.secureDocument.secureFile.file_hash == null) {
                            secureDocumentHash = this.cacheImage.secureDocument.fileHash;
                            secureDocumentKey = secureDocumentKey3;
                        } else {
                            secureDocumentHash = this.cacheImage.secureDocument.secureFile.file_hash;
                            secureDocumentKey = secureDocumentKey3;
                        }
                    } else {
                        secureDocumentHash = null;
                        secureDocumentKey = null;
                    }
                    canDeleteFile = true;
                    boolean useNativeWebpLoader = false;
                    if (Build.VERSION.SDK_INT < 19) {
                        RandomAccessFile randomAccessFile = null;
                        try {
                            try {
                                try {
                                    randomAccessFile = new RandomAccessFile(cacheFileFinal, "r");
                                    byte[] bytes3 = this.cacheImage.imageType == 1 ? ImageLoader.headerThumb : ImageLoader.header;
                                    randomAccessFile.readFully(bytes3, 0, bytes3.length);
                                    String str = new String(bytes3).toLowerCase().toLowerCase();
                                    if (str.startsWith("riff") && str.endsWith("webp")) {
                                        useNativeWebpLoader = true;
                                    }
                                    randomAccessFile.close();
                                    randomAccessFile.close();
                                } catch (Exception e) {
                                    FileLog.e(e);
                                }
                            } catch (Exception e2) {
                                FileLog.e(e2);
                                if (randomAccessFile != null) {
                                    randomAccessFile.close();
                                }
                            }
                        } catch (Throwable e3) {
                            if (randomAccessFile != null) {
                                try {
                                    randomAccessFile.close();
                                } catch (Exception e4) {
                                    FileLog.e(e4);
                                }
                            }
                            throw e3;
                        }
                    }
                    String mediaThumbPath = null;
                    if (this.cacheImage.imageLocation.path != null) {
                        String location2 = this.cacheImage.imageLocation.path;
                        if (location2.startsWith("thumb://")) {
                            int idx = location2.indexOf(LogUtils.COLON, 8);
                            if (idx >= 0) {
                                mediaId = Long.valueOf(Long.parseLong(location2.substring(8, idx)));
                                mediaIsVideo = false;
                                mediaThumbPath = location2.substring(idx + 1);
                            }
                            canDeleteFile = false;
                            location = mediaThumbPath;
                        } else if (location2.startsWith("vthumb://")) {
                            int idx2 = location2.indexOf(LogUtils.COLON, 9);
                            if (idx2 >= 0) {
                                mediaId = Long.valueOf(Long.parseLong(location2.substring(9, idx2)));
                                mediaIsVideo = true;
                            }
                            canDeleteFile = false;
                            location = null;
                        } else if (!location2.startsWith("http")) {
                            canDeleteFile = false;
                            location = null;
                        }
                        opts = new BitmapFactory.Options();
                        opts.inSampleSize = 1;
                        if (Build.VERSION.SDK_INT < 21) {
                            opts.inPurgeable = true;
                        }
                        float w_filter3 = 0.0f;
                        float h_filter5 = 0.0f;
                        Bitmap image3 = null;
                        boolean force8888 = ImageLoader.this.canForce8888;
                        FileInputStream is3 = 1065353216;
                        if (this.cacheImage.filter == null) {
                            String[] args2 = this.cacheImage.filter.split("_");
                            if (args2.length >= 2) {
                                try {
                                    w_filter3 = Float.parseFloat(args2[0]) * AndroidUtilities.density;
                                    h_filter5 = Float.parseFloat(args2[1]) * AndroidUtilities.density;
                                } catch (Throwable th) {
                                    e = th;
                                    needInvert = false;
                                    FileLog.e(e);
                                    w_filter = w_filter3;
                                    h_filter2 = h_filter5;
                                    bitmap = image3;
                                    h_filter = is3;
                                    if (this.cacheImage.imageType == 1) {
                                    }
                                    Thread.interrupted();
                                    if (needInvert2) {
                                    }
                                    onPostExecute(image == null ? new ExtendedBitmapDrawable(image, needInvert2, orientation) : null);
                                }
                            }
                            if (this.cacheImage.filter.contains("b2")) {
                                image3 = 3;
                            } else if (this.cacheImage.filter.contains("b1")) {
                                image3 = 2;
                            } else if (this.cacheImage.filter.contains("b")) {
                                image3 = 1;
                            }
                            checkInversion = this.cacheImage.filter.contains("i");
                            if (this.cacheImage.filter.contains("f")) {
                                force8888 = true;
                            }
                            if (useNativeWebpLoader || w_filter3 == 0.0f || h_filter5 == 0.0f) {
                                image2 = null;
                                needInvert = false;
                            } else {
                                opts.inJustDecodeBounds = true;
                                try {
                                    if (mediaId == null || location != null) {
                                        needInvert = false;
                                        if (secureDocumentKey != null) {
                                            try {
                                                RandomAccessFile f = new RandomAccessFile(cacheFileFinal, "r");
                                                int len2 = (int) f.length();
                                                byte[] bytes4 = (byte[]) ImageLoader.bytesLocal.get();
                                                byte[] data2 = (bytes4 == null || bytes4.length < len2) ? null : bytes4;
                                                if (data2 == null) {
                                                    byte[] bytes5 = new byte[len2];
                                                    data2 = bytes5;
                                                    ImageLoader.bytesLocal.set(bytes5);
                                                }
                                                image2 = null;
                                                f.readFully(data2, 0, len2);
                                                f.close();
                                                EncryptedFileInputStream.decryptBytesWithKeyFile(data2, 0, len2, secureDocumentKey);
                                                byte[] hash = Utilities.computeSHA256(data2, 0, len2);
                                                boolean error = false;
                                                error = (secureDocumentHash == null || !Arrays.equals(hash, secureDocumentHash)) ? true : true;
                                                int offset = data2[0] & UByte.MAX_VALUE;
                                                int len3 = len2 - offset;
                                                if (!error) {
                                                    BitmapFactory.decodeByteArray(data2, offset, len3, opts);
                                                }
                                            } catch (Throwable th2) {
                                                e = th2;
                                                image = null;
                                                FileLog.e(e);
                                                w_filter = w_filter3;
                                                h_filter2 = h_filter5;
                                                bitmap = image3;
                                                h_filter = is3;
                                                if (this.cacheImage.imageType == 1) {
                                                }
                                                Thread.interrupted();
                                                if (needInvert2) {
                                                }
                                                onPostExecute(image == null ? new ExtendedBitmapDrawable(image, needInvert2, orientation) : null);
                                            }
                                        } else {
                                            image2 = null;
                                            FileInputStream is4 = inEncryptedFile2 ? new EncryptedFileInputStream(cacheFileFinal, this.cacheImage.encryptionKeyPath) : new FileInputStream(cacheFileFinal);
                                            BitmapFactory.decodeStream(is4, null, opts);
                                            is4.close();
                                        }
                                    } else if (mediaIsVideo) {
                                        try {
                                            needInvert = false;
                                            MediaStore.Video.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaId.longValue(), 1, opts);
                                            image2 = null;
                                        } catch (Throwable th3) {
                                            e = th3;
                                            needInvert = false;
                                            FileLog.e(e);
                                            w_filter = w_filter3;
                                            h_filter2 = h_filter5;
                                            bitmap = image3;
                                            h_filter = is3;
                                            if (this.cacheImage.imageType == 1) {
                                            }
                                            Thread.interrupted();
                                            if (needInvert2) {
                                            }
                                            onPostExecute(image == null ? new ExtendedBitmapDrawable(image, needInvert2, orientation) : null);
                                        }
                                    } else {
                                        needInvert = false;
                                        MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaId.longValue(), 1, opts);
                                        image2 = null;
                                    }
                                    float photoW = opts.outWidth;
                                    float photoH = opts.outHeight;
                                    if (w_filter3 < h_filter5 || photoW <= photoH) {
                                        float scaleFactor2 = photoW / w_filter3;
                                        scaleFactor = Math.min(scaleFactor2, photoH / h_filter5);
                                    } else {
                                        scaleFactor = Math.max(photoW / w_filter3, photoH / h_filter5);
                                    }
                                    if (scaleFactor < 1.2f) {
                                        scaleFactor = 1.0f;
                                    }
                                    opts.inJustDecodeBounds = false;
                                    if (scaleFactor <= 1.0f || (photoW <= w_filter3 && photoH <= h_filter5)) {
                                        opts.inSampleSize = (int) scaleFactor;
                                    } else {
                                        int sample = 1;
                                        do {
                                            sample *= 2;
                                        } while (sample * 2 < scaleFactor);
                                        opts.inSampleSize = sample;
                                    }
                                } catch (Throwable th4) {
                                    e = th4;
                                    image = "f";
                                }
                            }
                        } else {
                            image2 = null;
                            needInvert = false;
                            if (location != null) {
                                opts.inJustDecodeBounds = true;
                                opts.inPreferredConfig = force8888 ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
                                FileInputStream is5 = new FileInputStream(cacheFileFinal);
                                image = BitmapFactory.decodeStream(is5, null, opts);
                                try {
                                    is5.close();
                                    int photoW2 = opts.outWidth;
                                    int photoH2 = opts.outHeight;
                                    opts.inJustDecodeBounds = false;
                                    float scaleFactor3 = Math.max(photoW2 / ItemTouchHelper.Callback.DEFAULT_DRAG_ANIMATION_DURATION, photoH2 / ItemTouchHelper.Callback.DEFAULT_DRAG_ANIMATION_DURATION);
                                    if (scaleFactor3 < 1.0f) {
                                        scaleFactor3 = 1.0f;
                                    }
                                    if (scaleFactor3 > 1.0f) {
                                        int sample2 = 1;
                                        while (true) {
                                            sample2 *= 2;
                                            is2 = is5;
                                            if (sample2 * 2 >= scaleFactor3) {
                                                break;
                                            }
                                            is5 = is2;
                                        }
                                        opts.inSampleSize = sample2;
                                        is3 = is2;
                                    } else {
                                        is3 = is5;
                                        opts.inSampleSize = (int) scaleFactor3;
                                    }
                                    w_filter = w_filter3;
                                    h_filter2 = h_filter5;
                                    bitmap = image3;
                                    h_filter = is3;
                                } catch (Throwable th5) {
                                    e = th5;
                                    FileLog.e(e);
                                    w_filter = w_filter3;
                                    h_filter2 = h_filter5;
                                    bitmap = image3;
                                    h_filter = is3;
                                    if (this.cacheImage.imageType == 1) {
                                    }
                                    Thread.interrupted();
                                    if (needInvert2) {
                                    }
                                    onPostExecute(image == null ? new ExtendedBitmapDrawable(image, needInvert2, orientation) : null);
                                }
                                if (this.cacheImage.imageType == 1) {
                                    try {
                                        ImageLoader.this.lastCacheOutTime = System.currentTimeMillis();
                                        try {
                                        } catch (Throwable th6) {
                                            e = th6;
                                            image = image3;
                                            needInvert2 = needInvert;
                                        }
                                    } catch (Throwable th7) {
                                        e = th7;
                                        h_filter = h_filter2;
                                        needInvert2 = needInvert;
                                    }
                                    synchronized (this.sync) {
                                        try {
                                            if (this.isCancelled) {
                                                try {
                                                    return;
                                                } catch (Throwable th8) {
                                                    th = th8;
                                                    while (true) {
                                                        try {
                                                            break;
                                                        } catch (Throwable th9) {
                                                            th = th9;
                                                        }
                                                    }
                                                    throw th;
                                                }
                                            }
                                            try {
                                                if (useNativeWebpLoader) {
                                                    RandomAccessFile file = new RandomAccessFile(cacheFileFinal, "r");
                                                    ByteBuffer buffer = file.getChannel().map(FileChannel.MapMode.READ_ONLY, 0L, cacheFileFinal.length());
                                                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                                                    Bitmap image4 = image;
                                                    try {
                                                        bmOptions.inJustDecodeBounds = true;
                                                        h_filter = h_filter2;
                                                        Utilities.loadWebpImage(null, buffer, buffer.limit(), bmOptions, true);
                                                        image = Bitmaps.createBitmap(bmOptions.outWidth, bmOptions.outHeight, Bitmap.Config.ARGB_8888);
                                                        Utilities.loadWebpImage(image, buffer, buffer.limit(), null, !opts.inPurgeable);
                                                        file.close();
                                                    } catch (Throwable th10) {
                                                        e = th10;
                                                        h_filter = h_filter2;
                                                        image = image4;
                                                        needInvert2 = needInvert;
                                                        FileLog.e(e);
                                                        orientation = 0;
                                                        Thread.interrupted();
                                                        if (needInvert2) {
                                                        }
                                                        onPostExecute(image == null ? new ExtendedBitmapDrawable(image, needInvert2, orientation) : null);
                                                    }
                                                } else {
                                                    h_filter = h_filter2;
                                                    Bitmap image5 = image;
                                                    if (!opts.inPurgeable && secureDocumentKey == null) {
                                                        FileInputStream is6 = inEncryptedFile2 ? new EncryptedFileInputStream(cacheFileFinal, this.cacheImage.encryptionKeyPath) : new FileInputStream(cacheFileFinal);
                                                        image = BitmapFactory.decodeStream(is6, null, opts);
                                                        is6.close();
                                                    }
                                                    RandomAccessFile f2 = new RandomAccessFile(cacheFileFinal, "r");
                                                    int len4 = (int) f2.length();
                                                    int offset2 = 0;
                                                    byte[] bytesThumb = (byte[]) ImageLoader.bytesThumbLocal.get();
                                                    byte[] data3 = (bytesThumb == null || bytesThumb.length < len4) ? null : bytesThumb;
                                                    if (data3 == null) {
                                                        byte[] bytesThumb2 = new byte[len4];
                                                        data3 = bytesThumb2;
                                                        ImageLoader.bytesThumbLocal.set(bytesThumb2);
                                                    }
                                                    f2.readFully(data3, 0, len4);
                                                    f2.close();
                                                    boolean error2 = false;
                                                    if (secureDocumentKey != null) {
                                                        EncryptedFileInputStream.decryptBytesWithKeyFile(data3, 0, len4, secureDocumentKey);
                                                        byte[] hash2 = Utilities.computeSHA256(data3, 0, len4);
                                                        error2 = (secureDocumentHash == null || !Arrays.equals(hash2, secureDocumentHash)) ? true : true;
                                                        offset2 = data3[0] & UByte.MAX_VALUE;
                                                        len4 -= offset2;
                                                    } else if (inEncryptedFile2) {
                                                        EncryptedFileInputStream.decryptBytesWithKeyFile(data3, 0, len4, this.cacheImage.encryptionKeyPath);
                                                        image = error2 ? BitmapFactory.decodeByteArray(data3, offset2, len4, opts) : image5;
                                                    }
                                                    if (error2) {
                                                    }
                                                }
                                                if (image == null) {
                                                    if (cacheFileFinal.length() == 0 || this.cacheImage.filter == null) {
                                                        cacheFileFinal.delete();
                                                    }
                                                    needInvert2 = needInvert;
                                                } else {
                                                    if (this.cacheImage.filter != null) {
                                                        float bitmapW = image.getWidth();
                                                        float bitmapH = image.getHeight();
                                                        if (!opts.inPurgeable && w_filter != 0.0f && bitmapW != w_filter && bitmapW > w_filter + 20.0f) {
                                                            float scaleFactor4 = bitmapW / w_filter;
                                                            Bitmap scaledBitmap2 = Bitmaps.createScaledBitmap(image, (int) w_filter, (int) (bitmapH / scaleFactor4), true);
                                                            if (image != scaledBitmap2) {
                                                                image.recycle();
                                                                image = scaledBitmap2;
                                                            }
                                                        }
                                                    }
                                                    if (checkInversion) {
                                                        needInvert2 = Utilities.needInvert(image, opts.inPurgeable ? 0 : 1, image.getWidth(), image.getHeight(), image.getRowBytes()) != 0;
                                                    } else {
                                                        needInvert2 = needInvert;
                                                    }
                                                    try {
                                                        if (bitmap == 1) {
                                                            if (image.getConfig() == Bitmap.Config.ARGB_8888) {
                                                                Utilities.blurBitmap(image, 3, opts.inPurgeable ? 0 : 1, image.getWidth(), image.getHeight(), image.getRowBytes());
                                                            }
                                                        } else if (bitmap == 2) {
                                                            if (image.getConfig() == Bitmap.Config.ARGB_8888) {
                                                                Utilities.blurBitmap(image, 1, opts.inPurgeable ? 0 : 1, image.getWidth(), image.getHeight(), image.getRowBytes());
                                                            }
                                                        } else if (bitmap == 3) {
                                                            if (image.getConfig() == Bitmap.Config.ARGB_8888) {
                                                                Utilities.blurBitmap(image, 7, opts.inPurgeable ? 0 : 1, image.getWidth(), image.getHeight(), image.getRowBytes());
                                                                Utilities.blurBitmap(image, 7, opts.inPurgeable ? 0 : 1, image.getWidth(), image.getHeight(), image.getRowBytes());
                                                                Utilities.blurBitmap(image, 7, opts.inPurgeable ? 0 : 1, image.getWidth(), image.getHeight(), image.getRowBytes());
                                                            }
                                                        } else if (bitmap == null) {
                                                            if (opts.inPurgeable) {
                                                                Utilities.pinBitmap(image);
                                                            }
                                                        }
                                                    } catch (Throwable th11) {
                                                        e = th11;
                                                        FileLog.e(e);
                                                        orientation = 0;
                                                        Thread.interrupted();
                                                        if (needInvert2) {
                                                        }
                                                        onPostExecute(image == null ? new ExtendedBitmapDrawable(image, needInvert2, orientation) : null);
                                                    }
                                                }
                                            } catch (Throwable th12) {
                                                e = th12;
                                                needInvert2 = needInvert;
                                            }
                                            orientation = 0;
                                        } catch (Throwable th13) {
                                            th = th13;
                                        }
                                    }
                                } else {
                                    h_filter3 = h_filter2;
                                    boolean mediaIsVideo2 = mediaIsVideo;
                                    Bitmap image6 = image;
                                    int delay = mediaId != null ? 0 : 20;
                                    try {
                                        if (delay != 0) {
                                            try {
                                                if (ImageLoader.this.lastCacheOutTime != 0) {
                                                    inEncryptedFile = inEncryptedFile2;
                                                    secureDocumentKey2 = secureDocumentKey;
                                                    if (ImageLoader.this.lastCacheOutTime > System.currentTimeMillis() - delay) {
                                                        try {
                                                            if (Build.VERSION.SDK_INT < 21) {
                                                                Thread.sleep(delay);
                                                            }
                                                        } catch (Throwable th14) {
                                                            orientation = 0;
                                                            image = image6;
                                                            needInvert2 = needInvert;
                                                        }
                                                    }
                                                    ImageLoader.this.lastCacheOutTime = System.currentTimeMillis();
                                                    synchronized (this.sync) {
                                                        try {
                                                            if (this.isCancelled) {
                                                                try {
                                                                    return;
                                                                } catch (Throwable th15) {
                                                                    th = th15;
                                                                    while (true) {
                                                                        try {
                                                                            break;
                                                                        } catch (Throwable th16) {
                                                                            th = th16;
                                                                        }
                                                                    }
                                                                    throw th;
                                                                }
                                                            }
                                                        } catch (Throwable th17) {
                                                            th = th17;
                                                        }
                                                    }
                                                    try {
                                                        break;
                                                        throw th;
                                                    } catch (Throwable th18) {
                                                        orientation = 0;
                                                        image = image6;
                                                        needInvert2 = needInvert;
                                                    }
                                                }
                                            } catch (Throwable th19) {
                                                orientation = 0;
                                                image = image6;
                                                needInvert2 = needInvert;
                                            }
                                        }
                                        ImageLoader.this.lastCacheOutTime = System.currentTimeMillis();
                                        synchronized (this.sync) {
                                        }
                                    } catch (Throwable th20) {
                                        orientation = 0;
                                        image = image6;
                                        needInvert2 = needInvert;
                                    }
                                    inEncryptedFile = inEncryptedFile2;
                                    secureDocumentKey2 = secureDocumentKey;
                                }
                                Thread.interrupted();
                                if (needInvert2 && orientation == 0) {
                                    onPostExecute(image != null ? new BitmapDrawable(image) : null);
                                    return;
                                } else {
                                    onPostExecute(image == null ? new ExtendedBitmapDrawable(image, needInvert2, orientation) : null);
                                }
                            }
                        }
                        image = image2;
                        w_filter = w_filter3;
                        h_filter2 = h_filter5;
                        bitmap = image3;
                        h_filter = is3;
                        if (this.cacheImage.imageType == 1) {
                        }
                        Thread.interrupted();
                        if (needInvert2) {
                        }
                        onPostExecute(image == null ? new ExtendedBitmapDrawable(image, needInvert2, orientation) : null);
                    }
                    location = null;
                    opts = new BitmapFactory.Options();
                    opts.inSampleSize = 1;
                    if (Build.VERSION.SDK_INT < 21) {
                    }
                    float w_filter32 = 0.0f;
                    float h_filter52 = 0.0f;
                    Bitmap image32 = null;
                    boolean force88882 = ImageLoader.this.canForce8888;
                    FileInputStream is32 = 1065353216;
                    if (this.cacheImage.filter == null) {
                    }
                    image = image2;
                    w_filter = w_filter32;
                    h_filter2 = h_filter52;
                    bitmap = image32;
                    h_filter = is32;
                    if (this.cacheImage.imageType == 1) {
                    }
                    Thread.interrupted();
                    if (needInvert2) {
                    }
                    onPostExecute(image == null ? new ExtendedBitmapDrawable(image, needInvert2, orientation) : null);
                }
            }
            try {
                is.getChannel().position(0L);
                image = BitmapFactory.decodeStream(is, null, opts);
                is.close();
                location = secureDocumentKey2;
                if (image == null) {
                    if (canDeleteFile) {
                        try {
                            if (cacheFileFinal.length() == 0 || this.cacheImage.filter == null) {
                                cacheFileFinal.delete();
                            }
                        } catch (Throwable th21) {
                            needInvert2 = needInvert;
                        }
                    }
                    needInvert2 = needInvert;
                } else {
                    boolean blured2 = false;
                    try {
                        if (this.cacheImage.filter != null) {
                            float bitmapW2 = image.getWidth();
                            float bitmapH2 = image.getHeight();
                            if (opts.inPurgeable || w_filter == 0.0f || bitmapW2 == w_filter || bitmapW2 <= 20.0f + w_filter) {
                                blured = false;
                            } else {
                                if (bitmapW2 <= bitmapH2 || w_filter <= h_filter3) {
                                    blured = false;
                                    float scaleFactor5 = bitmapH2 / h_filter3;
                                    try {
                                        scaledBitmap = Bitmaps.createScaledBitmap(image, (int) (bitmapW2 / scaleFactor5), (int) h_filter3, true);
                                    } catch (Throwable th22) {
                                        needInvert2 = needInvert;
                                    }
                                } else {
                                    float scaleFactor6 = bitmapW2 / w_filter;
                                    blured = false;
                                    try {
                                        scaledBitmap = Bitmaps.createScaledBitmap(image, (int) w_filter, (int) (bitmapH2 / scaleFactor6), true);
                                    } catch (Throwable th23) {
                                        needInvert2 = needInvert;
                                    }
                                }
                                if (image != scaledBitmap) {
                                    image.recycle();
                                    image = scaledBitmap;
                                }
                            }
                            if (image != null) {
                                if (checkInversion) {
                                    Bitmap b = image;
                                    try {
                                        int w2 = image.getWidth();
                                        Bitmap b2 = w2 * image.getHeight() > 22500 ? Bitmaps.createScaledBitmap(image, 100, 100, false) : b;
                                        int i = opts.inPurgeable ? 0 : 1;
                                        int w3 = b2.getWidth();
                                        try {
                                            boolean needInvert3 = Utilities.needInvert(b2, i, w3, b2.getHeight(), b2.getRowBytes()) != 0;
                                            if (b2 != image) {
                                                try {
                                                    b2.recycle();
                                                } catch (Throwable th24) {
                                                    needInvert2 = needInvert3;
                                                }
                                            }
                                            needInvert = needInvert3;
                                        } catch (Throwable th25) {
                                            needInvert2 = needInvert;
                                        }
                                    } catch (Throwable th26) {
                                        needInvert2 = needInvert;
                                    }
                                }
                                if (bitmap == null || bitmapH2 >= 100.0f || bitmapW2 >= 100.0f) {
                                    blured2 = blured;
                                    needInvert2 = needInvert;
                                } else {
                                    if (image.getConfig() == Bitmap.Config.ARGB_8888) {
                                        Utilities.blurBitmap(image, 3, opts.inPurgeable ? 0 : 1, image.getWidth(), image.getHeight(), image.getRowBytes());
                                    }
                                    blured2 = true;
                                    needInvert2 = needInvert;
                                }
                            } else {
                                blured2 = blured;
                                needInvert2 = needInvert;
                            }
                        } else {
                            needInvert2 = needInvert;
                        }
                        if (!blured2) {
                            try {
                                if (opts.inPurgeable) {
                                    Utilities.pinBitmap(image);
                                }
                            } catch (Throwable th27) {
                            }
                        }
                    } catch (Throwable th28) {
                        needInvert2 = needInvert;
                    }
                }
            } catch (Throwable th29) {
                needInvert2 = needInvert;
            }
            Thread.interrupted();
            if (needInvert2) {
            }
            onPostExecute(image == null ? new ExtendedBitmapDrawable(image, needInvert2, orientation) : null);
        }

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

        public void lambda$onPostExecute$1$ImageLoader$CacheOutTask(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.lambda$null$0$ImageLoader$CacheOutTask(toSetFinal, decrementKetFinal);
                }
            });
        }

        public void lambda$null$0$ImageLoader$CacheOutTask(Drawable toSetFinal, String decrementKetFinal) {
            this.cacheImage.setImageAndClear(toSetFinal, decrementKetFinal);
        }

        public void cancel() {
            synchronized (this.sync) {
                try {
                    this.isCancelled = true;
                    if (this.runningThread != null) {
                        this.runningThread.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.lambda$setImageAndClear$0$ImageLoader$CacheImage(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 lambda$setImageAndClear$0$ImageLoader$CacheImage(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.lambda$fileDidUploaded$2$ImageLoader$3(i, location, inputFile, inputEncryptedFile, key, iv, totalFileSize, apply);
                }
            });
        }

        public void lambda$fileDidUploaded$2$ImageLoader$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.lambda$fileDidFailedUpload$4$ImageLoader$3(i, location, isEncrypted);
                }
            });
        }

        public void lambda$fileDidFailedUpload$4$ImageLoader$3(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.lambda$fileDidLoaded$5$ImageLoader$3(finalFile, location, i, type);
                }
            });
        }

        public void lambda$fileDidLoaded$5$ImageLoader$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.lambda$fileDidFailedLoad$6$ImageLoader$3(location, canceled, i);
                }
            });
        }

        public void lambda$fileDidFailedLoad$6$ImageLoader$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.lambda$onReceive$0$ImageLoader$4();
                }
            };
            if ("android.intent.action.MEDIA_UNMOUNTED".equals(intent.getAction())) {
                AndroidUtilities.runOnUIThread(r, 1000L);
            } else {
                r.run();
            }
        }

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

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

    public void lambda$checkMediaPaths$1$ImageLoader() {
        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(), "Cchen");
                this.appPath = file;
                file.mkdirs();
                if (this.appPath.isDirectory()) {
                    try {
                        File imagePath = new File(this.appPath, "Cchen 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, "Cchen 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, "Cchen 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, "Cchen 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) {
                            file.close();
                            return false;
                        }
                        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) {
                        file.close();
                        return false;
                    }
                    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.lambda$cancelLoadingForImageReceiver$2$ImageLoader(cancelAll, imageReceiver);
            }
        });
    }

    public void lambda$cancelLoadingForImageReceiver$2$ImageLoader(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()) {
            LruCache<BitmapDrawable> lruCache = this.memCache;
            return lruCache.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 lambda$replaceImageInCache$3$ImageLoader(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.lambda$replaceImageInCache$3$ImageLoader(oldKey, newKey, newLocation);
                }
            });
        } else {
            lambda$replaceImageInCache$3$ImageLoader(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.lambda$cancelForceLoadingForImageReceiver$4$ImageLoader(key);
            }
        });
    }

    public void lambda$cancelForceLoadingForImageReceiver$4$ImageLoader(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.lambda$createLoadOperationForImageReceiver$5$ImageLoader(thumb, url, key, finalTag, imageReceiver, filter, imageType, guid, imageLocation, currentKeyQuality, parentObject, qualityDocument, finalIsNeedsQualityThumb, shouldGenerateQualityThumb, cacheType, size, ext, currentAccount);
            }
        });
    }

    public void lambda$createLoadOperationForImageReceiver$5$ImageLoader(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;
        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) {
                    if (MessageObject.isGifDocument(imageLocation.webFile) || MessageObject.isGifDocument(imageLocation.document) || MessageObject.isRoundVideoDocument(imageLocation.document)) {
                        img.animatedFile = true;
                    } else if (imageLocation.path != null) {
                        String location3 = imageLocation.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 (imageLocation.photoSize instanceof TLRPC.TL_photoStrippedSize) {
                        onlyCache3 = true;
                        str2 = url;
                        i = cacheType;
                    } else if (imageLocation.secureDocument != null) {
                        img.secureDocument = imageLocation.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 (imageLocation.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);
                                    boolean cacheFileExists5 = cacheFileExists4;
                                    StringBuilder sb = new StringBuilder();
                                    sb.append(str2);
                                    fileSize2 = 0;
                                    sb.append(".enc");
                                    cacheFile5 = new File(cacheFile6, sb.toString());
                                    cacheFileExists4 = cacheFileExists5;
                                } else {
                                    fileSize2 = 0;
                                }
                                if (imageLocation.document != null) {
                                    img.lottieFile = "application/x-tgsticker".equals(imageLocation.document.mime_type);
                                }
                                onlyCache3 = onlyCache5;
                                fileSize3 = fileSize2;
                            }
                            cacheFile5 = new File(FileLoader.getDirectory(4), str2);
                            if (!cacheFile5.exists()) {
                            }
                            if (imageLocation.document != null) {
                            }
                            onlyCache3 = onlyCache5;
                            fileSize3 = fileSize2;
                        }
                        if (imageLocation.document != null) {
                            TLRPC.Document document = imageLocation.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 (imageLocation.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 = imageLocation;
                img.ext = ext;
                img.currentAccount = currentAccount;
                img.parentObject = parentObject;
                if (imageLocation.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 = imageLocation;
                    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 (imageLocation.path != null) {
                    String file = Utilities.MD5(imageLocation.path);
                    File cacheDir = FileLoader.getDirectory(4);
                    img.tempFilePath = new File(cacheDir, file + "_temp.jpg");
                    img.finalFilePath = cacheFile2;
                    if (imageLocation.path.startsWith(str)) {
                        img.artworkTask = new ArtworkLoadTask(img);
                        this.artworkTasks.add(img.artworkTask);
                        runArtworkTasks(false);
                        return;
                    }
                    img.httpTask = new HttpImageTask(img, size);
                    this.httpTasks.add(img.httpTask);
                    runHttpTasks(false);
                    return;
                }
                if (imageLocation.location != null) {
                    if (cacheType == 0 && (size <= 0 || imageLocation.key != null)) {
                        localCacheType = 1;
                    } else {
                        localCacheType = cacheType;
                    }
                    FileLoader.getInstance(currentAccount).loadFile(imageLocation, parentObject, ext, thumb != 0 ? 2 : 1, localCacheType);
                } else if (imageLocation.document != null) {
                    FileLoader.getInstance(currentAccount).loadFile(imageLocation.document, parentObject, thumb != 0 ? 2 : 1, i3);
                } else if (imageLocation.secureDocument != null) {
                    FileLoader.getInstance(currentAccount).loadFile(imageLocation.secureDocument, thumb != 0 ? 2 : 1);
                } else if (imageLocation.webFile != null) {
                    FileLoader.getInstance(currentAccount).loadFile(imageLocation.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.lambda$httpFileLoadError$6$ImageLoader(location);
            }
        });
    }

    public void lambda$httpFileLoadError$6$ImageLoader(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.lambda$artworkLoadError$7$ImageLoader(location);
            }
        });
    }

    public void lambda$artworkLoadError$7$ImageLoader(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.lambda$fileDidLoaded$8$ImageLoader(location, type, finalFile);
            }
        });
    }

    public void lambda$fileDidLoaded$8$ImageLoader(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.lambda$fileDidFailedLoad$9$ImageLoader(location);
            }
        });
    }

    public void lambda$fileDidFailedLoad$9$ImageLoader(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);
        File directory = FileLoader.getDirectory(4);
        return new File(directory, 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 directory = FileLoader.getDirectory(4);
        File file = new File(directory, 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.lambda$runHttpFileLoadTasks$11$ImageLoader(oldTask, reason);
            }
        });
    }

    public void lambda$runHttpFileLoadTasks$11$ImageLoader(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.lambda$null$10$ImageLoader(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 lambda$null$10$ImageLoader(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;
            }
            int sample2 = Build.VERSION.SDK_INT;
            bmOptions.inPurgeable = sample2 < 21;
            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();
                    if (orientation == 3) {
                        matrix.postRotate(180.0f);
                    } else if (orientation == 6) {
                        matrix.postRotate(90.0f);
                    } else if (orientation == 8) {
                        matrix.postRotate(270.0f);
                    }
                } 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;
                }
            } else if (uri == null) {
                return null;
            } else {
                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) {
                    FileLog.e(e4);
                    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) {
        }
        int sample22 = Build.VERSION.SDK_INT;
        bmOptions.inPurgeable = sample22 < 21;
        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;
                    }
                }
            } else 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;
                    }
                }
            } else 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);
        }
    }
}