FileBackend.java

   1package eu.siacs.conversations.persistance;
   2
   3import android.content.ContentResolver;
   4import android.content.Context;
   5import android.content.res.AssetFileDescriptor;
   6import android.content.res.Resources;
   7import android.database.Cursor;
   8import android.graphics.Bitmap;
   9import android.graphics.BitmapFactory;
  10import android.graphics.Canvas;
  11import android.graphics.Color;
  12import android.graphics.drawable.BitmapDrawable;
  13import android.graphics.drawable.Drawable;
  14import android.graphics.ImageDecoder;
  15import android.graphics.Matrix;
  16import android.graphics.Paint;
  17import android.graphics.Rect;
  18import android.graphics.RectF;
  19import android.graphics.pdf.PdfRenderer;
  20import android.media.MediaMetadataRetriever;
  21import android.media.MediaScannerConnection;
  22import android.net.Uri;
  23import android.os.Build;
  24import android.os.Environment;
  25import android.os.ParcelFileDescriptor;
  26import android.provider.MediaStore;
  27import android.provider.OpenableColumns;
  28import android.system.Os;
  29import android.system.StructStat;
  30import android.util.Base64;
  31import android.util.Base64OutputStream;
  32import android.util.DisplayMetrics;
  33import android.util.Pair;
  34import android.util.Log;
  35import android.util.LruCache;
  36
  37import androidx.annotation.RequiresApi;
  38import androidx.annotation.StringRes;
  39import androidx.core.content.FileProvider;
  40import androidx.documentfile.provider.DocumentFile;
  41import androidx.exifinterface.media.ExifInterface;
  42
  43import com.caverock.androidsvg.SVG;
  44import com.caverock.androidsvg.SVGParseException;
  45
  46import com.cheogram.android.BobTransfer;
  47
  48import com.google.common.base.Strings;
  49import com.google.common.collect.ImmutableList;
  50import com.google.common.io.ByteStreams;
  51
  52import com.madebyevan.thumbhash.ThumbHash;
  53
  54import com.wolt.blurhashkt.BlurHashDecoder;
  55
  56import java.io.ByteArrayInputStream;
  57import java.io.ByteArrayOutputStream;
  58import java.io.Closeable;
  59import java.io.File;
  60import java.io.FileDescriptor;
  61import java.io.FileInputStream;
  62import java.io.FileNotFoundException;
  63import java.io.FileOutputStream;
  64import java.io.IOException;
  65import java.io.InputStream;
  66import java.io.OutputStream;
  67import java.net.ServerSocket;
  68import java.net.Socket;
  69import java.nio.ByteBuffer;
  70import java.security.DigestOutputStream;
  71import java.security.MessageDigest;
  72import java.security.NoSuchAlgorithmException;
  73import java.text.SimpleDateFormat;
  74import java.util.ArrayList;
  75import java.util.Arrays;
  76import java.util.Date;
  77import java.util.List;
  78import java.util.Locale;
  79import java.util.UUID;
  80
  81import io.ipfs.cid.Cid;
  82
  83import eu.siacs.conversations.Config;
  84import eu.siacs.conversations.R;
  85import eu.siacs.conversations.entities.DownloadableFile;
  86import eu.siacs.conversations.entities.Message;
  87import eu.siacs.conversations.services.AttachFileToConversationRunnable;
  88import eu.siacs.conversations.services.XmppConnectionService;
  89import eu.siacs.conversations.ui.adapter.MediaAdapter;
  90import eu.siacs.conversations.ui.util.Attachment;
  91import eu.siacs.conversations.utils.CryptoHelper;
  92import eu.siacs.conversations.utils.FileUtils;
  93import eu.siacs.conversations.utils.FileWriterException;
  94import eu.siacs.conversations.utils.MimeUtils;
  95import eu.siacs.conversations.xmpp.pep.Avatar;
  96import eu.siacs.conversations.xml.Element;
  97
  98public class FileBackend {
  99
 100    private static final Object THUMBNAIL_LOCK = new Object();
 101
 102    private static final SimpleDateFormat IMAGE_DATE_FORMAT =
 103            new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
 104
 105    private static final String FILE_PROVIDER = ".files";
 106    private static final float IGNORE_PADDING = 0.15f;
 107    private final XmppConnectionService mXmppConnectionService;
 108
 109    private static final List<String> STORAGE_TYPES;
 110
 111    static {
 112        final ImmutableList.Builder<String> builder =
 113                new ImmutableList.Builder<String>()
 114                        .add(
 115                                Environment.DIRECTORY_DOWNLOADS,
 116                                Environment.DIRECTORY_PICTURES,
 117                                Environment.DIRECTORY_MOVIES);
 118        if (Build.VERSION.SDK_INT >= 19) {
 119            builder.add(Environment.DIRECTORY_DOCUMENTS);
 120        }
 121        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
 122            builder.add(Environment.DIRECTORY_RECORDINGS);
 123        }
 124        STORAGE_TYPES = builder.build();
 125    }
 126
 127    public FileBackend(XmppConnectionService service) {
 128        this.mXmppConnectionService = service;
 129    }
 130
 131    public static long getFileSize(Context context, Uri uri) {
 132        try (final Cursor cursor =
 133                context.getContentResolver().query(uri, null, null, null, null)) {
 134            if (cursor != null && cursor.moveToFirst()) {
 135                final int index = cursor.getColumnIndex(OpenableColumns.SIZE);
 136                if (index == -1) {
 137                    return -1;
 138                }
 139                return cursor.getLong(index);
 140            }
 141            return -1;
 142        } catch (final Exception ignored) {
 143            return -1;
 144        }
 145    }
 146
 147    public static boolean allFilesUnderSize(
 148            Context context, List<Attachment> attachments, long max) {
 149        final boolean compressVideo =
 150                !AttachFileToConversationRunnable.getVideoCompression(context)
 151                        .equals("uncompressed");
 152        if (max <= 0) {
 153            Log.d(Config.LOGTAG, "server did not report max file size for http upload");
 154            return true; // exception to be compatible with HTTP Upload < v0.2
 155        }
 156        for (Attachment attachment : attachments) {
 157            if (attachment.getType() != Attachment.Type.FILE) {
 158                continue;
 159            }
 160            String mime = attachment.getMime();
 161            if (mime != null && mime.startsWith("video/") && compressVideo) {
 162                try {
 163                    Dimensions dimensions =
 164                            FileBackend.getVideoDimensions(context, attachment.getUri());
 165                    if (dimensions.getMin() > 720) {
 166                        Log.d(
 167                                Config.LOGTAG,
 168                                "do not consider video file with min width larger than 720 for size check");
 169                        continue;
 170                    }
 171                } catch (final IOException | NotAVideoFile e) {
 172                    // ignore and fall through
 173                }
 174            }
 175            if (FileBackend.getFileSize(context, attachment.getUri()) > max) {
 176                Log.d(
 177                        Config.LOGTAG,
 178                        "not all files are under "
 179                                + max
 180                                + " bytes. suggesting falling back to jingle");
 181                return false;
 182            }
 183        }
 184        return true;
 185    }
 186
 187    public static File getBackupDirectory(final Context context) {
 188        final File conversationsDownloadDirectory =
 189                new File(
 190                        Environment.getExternalStoragePublicDirectory(
 191                                Environment.DIRECTORY_DOWNLOADS),
 192                        context.getString(R.string.app_name));
 193        return new File(conversationsDownloadDirectory, "Backup");
 194    }
 195
 196    public static File getLegacyBackupDirectory(final String app) {
 197        final File appDirectory = new File(Environment.getExternalStorageDirectory(), app);
 198        return new File(appDirectory, "Backup");
 199    }
 200
 201    private static Bitmap rotate(final Bitmap bitmap, final int degree) {
 202        if (degree == 0) {
 203            return bitmap;
 204        }
 205        final int w = bitmap.getWidth();
 206        final int h = bitmap.getHeight();
 207        final Matrix matrix = new Matrix();
 208        matrix.postRotate(degree);
 209        final Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
 210        if (!bitmap.isRecycled()) {
 211            bitmap.recycle();
 212        }
 213        return result;
 214    }
 215
 216    public static boolean isPathBlacklisted(String path) {
 217        final String androidDataPath =
 218                Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/";
 219        final File f = new File(path);
 220        return path.startsWith(androidDataPath) || !f.canRead();
 221    }
 222
 223    private static Paint createAntiAliasingPaint() {
 224        Paint paint = new Paint();
 225        paint.setAntiAlias(true);
 226        paint.setFilterBitmap(true);
 227        paint.setDither(true);
 228        return paint;
 229    }
 230
 231    public static Uri getUriForUri(Context context, Uri uri) {
 232        if ("file".equals(uri.getScheme())) {
 233            return getUriForFile(context, new File(uri.getPath()));
 234        } else {
 235            return uri;
 236        }
 237    }
 238
 239    public static Uri getUriForFile(Context context, File file) {
 240        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) {
 241            try {
 242                return FileProvider.getUriForFile(context, getAuthority(context), file);
 243            } catch (IllegalArgumentException e) {
 244                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 245                    throw new SecurityException(e);
 246                } else {
 247                    return Uri.fromFile(file);
 248                }
 249            }
 250        } else {
 251            return Uri.fromFile(file);
 252        }
 253    }
 254
 255    public static String getAuthority(Context context) {
 256        return context.getPackageName() + FILE_PROVIDER;
 257    }
 258
 259    private static boolean hasAlpha(final Bitmap bitmap) {
 260        final int w = bitmap.getWidth();
 261        final int h = bitmap.getHeight();
 262        final int yStep = Math.max(1, w / 100);
 263        final int xStep = Math.max(1, h / 100);
 264        for (int x = 0; x < w; x += xStep) {
 265            for (int y = 0; y < h; y += yStep) {
 266                if (Color.alpha(bitmap.getPixel(x, y)) < 255) {
 267                    return true;
 268                }
 269            }
 270        }
 271        return false;
 272    }
 273
 274    private static int calcSampleSize(File image, int size) {
 275        BitmapFactory.Options options = new BitmapFactory.Options();
 276        options.inJustDecodeBounds = true;
 277        BitmapFactory.decodeFile(image.getAbsolutePath(), options);
 278        return calcSampleSize(options, size);
 279    }
 280
 281    private static int calcSampleSize(BitmapFactory.Options options, int size) {
 282        int height = options.outHeight;
 283        int width = options.outWidth;
 284        int inSampleSize = 1;
 285
 286        if (height > size || width > size) {
 287            int halfHeight = height / 2;
 288            int halfWidth = width / 2;
 289
 290            while ((halfHeight / inSampleSize) > size && (halfWidth / inSampleSize) > size) {
 291                inSampleSize *= 2;
 292            }
 293        }
 294        return inSampleSize;
 295    }
 296
 297    private static Dimensions getVideoDimensions(Context context, Uri uri) throws NotAVideoFile, IOException {
 298        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
 299        try {
 300            mediaMetadataRetriever.setDataSource(context, uri);
 301        } catch (RuntimeException e) {
 302            throw new NotAVideoFile(e);
 303        }
 304        return getVideoDimensions(mediaMetadataRetriever);
 305    }
 306
 307    private static Dimensions getVideoDimensionsOfFrame(
 308            MediaMetadataRetriever mediaMetadataRetriever) {
 309        Bitmap bitmap = null;
 310        try {
 311            bitmap = mediaMetadataRetriever.getFrameAtTime();
 312            return new Dimensions(bitmap.getHeight(), bitmap.getWidth());
 313        } catch (Exception e) {
 314            return null;
 315        } finally {
 316            if (bitmap != null) {
 317                bitmap.recycle();
 318            }
 319        }
 320    }
 321
 322    private static Dimensions getVideoDimensions(MediaMetadataRetriever metadataRetriever)
 323            throws NotAVideoFile, IOException {
 324        String hasVideo =
 325                metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
 326        if (hasVideo == null) {
 327            throw new NotAVideoFile();
 328        }
 329        Dimensions dimensions = getVideoDimensionsOfFrame(metadataRetriever);
 330        if (dimensions != null) {
 331            return dimensions;
 332        }
 333        final int rotation = extractRotationFromMediaRetriever(metadataRetriever);
 334        boolean rotated = rotation == 90 || rotation == 270;
 335        int height;
 336        try {
 337            String h =
 338                    metadataRetriever.extractMetadata(
 339                            MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
 340            height = Integer.parseInt(h);
 341        } catch (Exception e) {
 342            height = -1;
 343        }
 344        int width;
 345        try {
 346            String w =
 347                    metadataRetriever.extractMetadata(
 348                            MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
 349            width = Integer.parseInt(w);
 350        } catch (Exception e) {
 351            width = -1;
 352        }
 353        try {
 354            metadataRetriever.release();
 355        } catch (final IOException e) {
 356            throw new NotAVideoFile();
 357        }
 358        Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height);
 359        return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
 360    }
 361
 362    private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
 363        String r =
 364                metadataRetriever.extractMetadata(
 365                        MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
 366        try {
 367            return Integer.parseInt(r);
 368        } catch (Exception e) {
 369            return 0;
 370        }
 371    }
 372
 373    public static void close(final Closeable stream) {
 374        if (stream != null) {
 375            try {
 376                stream.close();
 377            } catch (Exception e) {
 378                Log.d(Config.LOGTAG, "unable to close stream", e);
 379            }
 380        }
 381    }
 382
 383    public static void close(final Socket socket) {
 384        if (socket != null) {
 385            try {
 386                socket.close();
 387            } catch (IOException e) {
 388                Log.d(Config.LOGTAG, "unable to close socket", e);
 389            }
 390        }
 391    }
 392
 393    public static void close(final ServerSocket socket) {
 394        if (socket != null) {
 395            try {
 396                socket.close();
 397            } catch (IOException e) {
 398                Log.d(Config.LOGTAG, "unable to close server socket", e);
 399            }
 400        }
 401    }
 402
 403    public static boolean weOwnFile(final Uri uri) {
 404        if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
 405            return false;
 406        } else {
 407            return weOwnFileLollipop(uri);
 408        }
 409    }
 410
 411    private static boolean weOwnFileLollipop(final Uri uri) {
 412        final String path = uri.getPath();
 413        if (path == null) {
 414            return false;
 415        }
 416        try {
 417            File file = new File(path);
 418            FileDescriptor fd =
 419                    ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
 420                            .getFileDescriptor();
 421            StructStat st = Os.fstat(fd);
 422            return st.st_uid == android.os.Process.myUid();
 423        } catch (FileNotFoundException e) {
 424            return false;
 425        } catch (Exception e) {
 426            return true;
 427        }
 428    }
 429
 430    public static Uri getMediaUri(Context context, File file) {
 431        final String filePath = file.getAbsolutePath();
 432        try (final Cursor cursor =
 433                context.getContentResolver()
 434                        .query(
 435                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
 436                                new String[] {MediaStore.Images.Media._ID},
 437                                MediaStore.Images.Media.DATA + "=? ",
 438                                new String[] {filePath},
 439                                null)) {
 440            if (cursor != null && cursor.moveToFirst()) {
 441                final int id =
 442                        cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
 443                return Uri.withAppendedPath(
 444                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
 445            } else {
 446                return null;
 447            }
 448        } catch (final Exception e) {
 449            return null;
 450        }
 451    }
 452
 453    public static void updateFileParams(Message message, String url, long size) {
 454        Message.FileParams fileParams = new Message.FileParams();
 455        fileParams.url = url;
 456        fileParams.size = size;
 457        message.setFileParams(fileParams);
 458    }
 459
 460    public Bitmap getPreviewForUri(Attachment attachment, int size, boolean cacheOnly) {
 461        final String key = "attachment_" + attachment.getUuid().toString() + "_" + size;
 462        final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
 463        Drawable drawable = cache.get(key);
 464        if (drawable != null || cacheOnly) {
 465            return drawDrawable(drawable);
 466        }
 467        Bitmap bitmap = null;
 468        final String mime = attachment.getMime();
 469        if ("application/pdf".equals(mime)) {
 470            bitmap = cropCenterSquarePdf(attachment.getUri(), size);
 471            drawOverlay(
 472                    bitmap,
 473                    paintOverlayBlackPdf(bitmap)
 474                            ? R.drawable.open_pdf_black
 475                            : R.drawable.open_pdf_white,
 476                    0.75f);
 477        } else if (mime != null && mime.startsWith("video/")) {
 478            bitmap = cropCenterSquareVideo(attachment.getUri(), size);
 479            drawOverlay(
 480                    bitmap,
 481                    paintOverlayBlack(bitmap)
 482                            ? R.drawable.play_video_black
 483                            : R.drawable.play_video_white,
 484                    0.75f);
 485        } else {
 486            bitmap = cropCenterSquare(attachment.getUri(), size);
 487            if (bitmap != null && "image/gif".equals(mime)) {
 488                Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
 489                drawOverlay(
 490                        withGifOverlay,
 491                        paintOverlayBlack(withGifOverlay)
 492                                ? R.drawable.play_gif_black
 493                                : R.drawable.play_gif_white,
 494                        1.0f);
 495                bitmap.recycle();
 496                bitmap = withGifOverlay;
 497            }
 498        }
 499        if (key != null && bitmap != null) {
 500            cache.put(key, new BitmapDrawable(bitmap));
 501        }
 502        return bitmap;
 503    }
 504
 505    public void updateMediaScanner(File file) {
 506        updateMediaScanner(file, null);
 507    }
 508
 509    public void updateMediaScanner(File file, final Runnable callback) {
 510        MediaScannerConnection.scanFile(
 511                mXmppConnectionService,
 512                new String[] {file.getAbsolutePath()},
 513                null,
 514                new MediaScannerConnection.MediaScannerConnectionClient() {
 515                    @Override
 516                    public void onMediaScannerConnected() {}
 517
 518                    @Override
 519                    public void onScanCompleted(String path, Uri uri) {
 520                        if (callback != null && file.getAbsolutePath().equals(path)) {
 521                            callback.run();
 522                        } else {
 523                            Log.d(Config.LOGTAG, "media scanner scanned wrong file");
 524                            if (callback != null) {
 525                                callback.run();
 526                            }
 527                        }
 528                    }
 529                });
 530    }
 531
 532    public boolean deleteFile(Message message) {
 533        File file = getFile(message);
 534        if (file.delete()) {
 535            message.setDeleted(true);
 536            updateMediaScanner(file);
 537            return true;
 538        } else {
 539            return false;
 540        }
 541    }
 542
 543    public DownloadableFile getFile(Message message) {
 544        return getFile(message, true);
 545    }
 546
 547    public DownloadableFile getFileForPath(String path) {
 548        return getFileForPath(
 549                path,
 550                MimeUtils.guessMimeTypeFromExtension(MimeUtils.extractRelevantExtension(path)));
 551    }
 552
 553    private DownloadableFile getFileForPath(final String path, final String mime) {
 554        if (path.startsWith("/")) {
 555            return new DownloadableFile(path);
 556        } else {
 557            return getLegacyFileForFilename(path, mime);
 558        }
 559    }
 560
 561    public DownloadableFile getLegacyFileForFilename(final String filename, final String mime) {
 562        if (Strings.isNullOrEmpty(mime)) {
 563            return new DownloadableFile(getLegacyStorageLocation("Files"), filename);
 564        } else if (mime.startsWith("image/")) {
 565            return new DownloadableFile(getLegacyStorageLocation("Images"), filename);
 566        } else if (mime.startsWith("video/")) {
 567            return new DownloadableFile(getLegacyStorageLocation("Videos"), filename);
 568        } else {
 569            return new DownloadableFile(getLegacyStorageLocation("Files"), filename);
 570        }
 571    }
 572
 573    public boolean isInternalFile(final File file) {
 574        final File internalFile = getFileForPath(file.getName());
 575        return file.getAbsolutePath().equals(internalFile.getAbsolutePath());
 576    }
 577
 578    public DownloadableFile getFile(Message message, boolean decrypted) {
 579        final boolean encrypted =
 580                !decrypted
 581                        && (message.getEncryption() == Message.ENCRYPTION_PGP
 582                                || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
 583        String path = message.getRelativeFilePath();
 584        if (path == null) {
 585            path = message.getUuid();
 586        }
 587        final DownloadableFile file = getFileForPath(path, message.getMimeType());
 588        if (encrypted) {
 589            return new DownloadableFile(
 590                    mXmppConnectionService.getCacheDir(),
 591                    String.format("%s.%s", file.getName(), "pgp"));
 592        } else {
 593            return file;
 594        }
 595    }
 596
 597    public List<Attachment> convertToAttachments(List<DatabaseBackend.FilePath> relativeFilePaths) {
 598        final List<Attachment> attachments = new ArrayList<>();
 599        for (final DatabaseBackend.FilePath relativeFilePath : relativeFilePaths) {
 600            final String mime =
 601                    MimeUtils.guessMimeTypeFromExtension(
 602                            MimeUtils.extractRelevantExtension(relativeFilePath.path));
 603            final File file = getFileForPath(relativeFilePath.path, mime);
 604            attachments.add(Attachment.of(relativeFilePath.uuid, file, mime));
 605        }
 606        return attachments;
 607    }
 608
 609    private File getLegacyStorageLocation(final String type) {
 610        if (Config.ONLY_INTERNAL_STORAGE) {
 611            return new File(mXmppConnectionService.getFilesDir(), type);
 612        } else {
 613            final File appDirectory =
 614                    new File(
 615                            Environment.getExternalStorageDirectory(),
 616                            mXmppConnectionService.getString(R.string.app_name));
 617            final File appMediaDirectory = new File(appDirectory, "Media");
 618            final String locationName =
 619                    String.format(
 620                            "%s %s", mXmppConnectionService.getString(R.string.app_name), type);
 621            return new File(appMediaDirectory, locationName);
 622        }
 623    }
 624
 625    private Bitmap resize(final Bitmap originalBitmap, int size) throws IOException {
 626        int w = originalBitmap.getWidth();
 627        int h = originalBitmap.getHeight();
 628        if (w <= 0 || h <= 0) {
 629            throw new IOException("Decoded bitmap reported bounds smaller 0");
 630        } else if (Math.max(w, h) > size) {
 631            int scalledW;
 632            int scalledH;
 633            if (w <= h) {
 634                scalledW = Math.max((int) (w / ((double) h / size)), 1);
 635                scalledH = size;
 636            } else {
 637                scalledW = size;
 638                scalledH = Math.max((int) (h / ((double) w / size)), 1);
 639            }
 640            final Bitmap result =
 641                    Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
 642            if (!originalBitmap.isRecycled()) {
 643                originalBitmap.recycle();
 644            }
 645            return result;
 646        } else {
 647            return originalBitmap;
 648        }
 649    }
 650
 651    public boolean useImageAsIs(final Uri uri) {
 652        final String path = getOriginalPath(uri);
 653        if (path == null || isPathBlacklisted(path)) {
 654            return false;
 655        }
 656        final File file = new File(path);
 657        long size = file.length();
 658        if (size == 0
 659                || size
 660                        >= mXmppConnectionService
 661                                .getResources()
 662                                .getInteger(R.integer.auto_accept_filesize)) {
 663            return false;
 664        }
 665        BitmapFactory.Options options = new BitmapFactory.Options();
 666        options.inJustDecodeBounds = true;
 667        try {
 668            for (Cid cid : calculateCids(uri)) {
 669                if (mXmppConnectionService.getUrlForCid(cid) != null) return true;
 670            }
 671            final InputStream inputStream =
 672                    mXmppConnectionService.getContentResolver().openInputStream(uri);
 673            BitmapFactory.decodeStream(inputStream, null, options);
 674            close(inputStream);
 675            if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
 676                return false;
 677            }
 678            return (options.outWidth <= Config.IMAGE_SIZE
 679                    && options.outHeight <= Config.IMAGE_SIZE
 680                    && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
 681        } catch (final IOException e) {
 682            Log.d(Config.LOGTAG, "unable to get image dimensions", e);
 683            return false;
 684        }
 685    }
 686
 687    public String getOriginalPath(final Uri uri) {
 688        return FileUtils.getPath(mXmppConnectionService, uri);
 689    }
 690
 691    public void copyFileToDocumentFile(Context ctx, File file, DocumentFile df) throws FileCopyException {
 692        Log.d(
 693                Config.LOGTAG,
 694                "copy file (" + file + ") to " + df);
 695        try (final InputStream is = new FileInputStream(file);
 696                final OutputStream os =
 697                        mXmppConnectionService.getContentResolver().openOutputStream(df.getUri())) {
 698            if (is == null) {
 699                throw new FileCopyException(R.string.error_file_not_found);
 700            }
 701            try {
 702                ByteStreams.copy(is, os);
 703                os.flush();
 704            } catch (IOException e) {
 705                throw new FileWriterException(file);
 706            }
 707        } catch (final FileNotFoundException e) {
 708            throw new FileCopyException(R.string.error_file_not_found);
 709        } catch (final FileWriterException e) {
 710            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 711        } catch (final SecurityException | IllegalStateException e) {
 712            throw new FileCopyException(R.string.error_security_exception);
 713        } catch (final IOException e) {
 714            throw new FileCopyException(R.string.error_io_exception);
 715        }
 716    }
 717
 718    private InputStream openInputStream(Uri uri) throws IOException {
 719        if (uri != null && "data".equals(uri.getScheme())) {
 720            String[] parts = uri.getSchemeSpecificPart().split(",", 2);
 721            byte[] data;
 722            if (Arrays.asList(parts[0].split(";")).contains("base64")) {
 723                String[] parts2 = parts[0].split(";", 2);
 724                parts[0] = parts2[0];
 725                data = Base64.decode(parts[1], 0);
 726            } else {
 727                try {
 728                    data = parts[1].getBytes("UTF-8");
 729                } catch (final IOException e) {
 730                    data = new byte[0];
 731                }
 732            }
 733            return new ByteArrayInputStream(data);
 734        }
 735        final InputStream is = mXmppConnectionService.getContentResolver().openInputStream(uri);
 736        if (is == null) throw new FileNotFoundException("File not found");
 737        return is;
 738    }
 739
 740    private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
 741        Log.d(
 742                Config.LOGTAG,
 743                "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
 744        file.getParentFile().mkdirs();
 745        try {
 746            if (!file.createNewFile() && file.length() > 0) {
 747                if (file.canRead() && file.getName().startsWith("zb2")) return; // We have this content already
 748                throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 749            }
 750        } catch (IOException e) {
 751            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 752        }
 753        try (final OutputStream os = new FileOutputStream(file);
 754                final InputStream is = openInputStream(uri)) {
 755            if (is == null) {
 756                throw new FileCopyException(R.string.error_file_not_found);
 757            }
 758            try {
 759                ByteStreams.copy(is, os);
 760            } catch (IOException e) {
 761                throw new FileWriterException(file);
 762            }
 763            try {
 764                os.flush();
 765            } catch (IOException e) {
 766                throw new FileWriterException(file);
 767            }
 768        } catch (final FileNotFoundException e) {
 769            cleanup(file);
 770            throw new FileCopyException(R.string.error_file_not_found);
 771        } catch (final FileWriterException e) {
 772            cleanup(file);
 773            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 774        } catch (final SecurityException | IllegalStateException e) {
 775            cleanup(file);
 776            throw new FileCopyException(R.string.error_security_exception);
 777        } catch (final IOException e) {
 778            cleanup(file);
 779            throw new FileCopyException(R.string.error_io_exception);
 780        }
 781    }
 782
 783    public void copyFileToPrivateStorage(Message message, Uri uri, String type)
 784            throws FileCopyException {
 785        String mime = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
 786        Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
 787        String extension = MimeUtils.guessExtensionFromMimeType(mime);
 788        if (extension == null) {
 789            Log.d(Config.LOGTAG, "extension from mime type was null");
 790            extension = getExtensionFromUri(uri);
 791        }
 792        if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
 793            extension = "oga";
 794        }
 795
 796        try {
 797            setupRelativeFilePath(message, uri, extension);
 798            copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
 799            final String name = getDisplayNameFromUri(uri);
 800            if (name != null) {
 801                message.getFileParams().setName(name);
 802            }
 803        } catch (final XmppConnectionService.BlockedMediaException e) {
 804            message.setRelativeFilePath(null);
 805            message.setDeleted(true);
 806        }
 807    }
 808
 809    private String getDisplayNameFromUri(final Uri uri) {
 810        final String[] projection = {OpenableColumns.DISPLAY_NAME};
 811        String filename = null;
 812        try (final Cursor cursor =
 813                mXmppConnectionService
 814                        .getContentResolver()
 815                        .query(uri, projection, null, null, null)) {
 816            if (cursor != null && cursor.moveToFirst()) {
 817                filename = cursor.getString(0);
 818            }
 819        } catch (final Exception e) {
 820            filename = null;
 821        }
 822        return filename;
 823    }
 824
 825    private String getExtensionFromUri(final Uri uri) {
 826        final String[] projection = {MediaStore.MediaColumns.DATA};
 827        String filename = null;
 828        try (final Cursor cursor =
 829                mXmppConnectionService
 830                        .getContentResolver()
 831                        .query(uri, projection, null, null, null)) {
 832            if (cursor != null && cursor.moveToFirst()) {
 833                filename = cursor.getString(0);
 834            }
 835        } catch (final Exception e) {
 836            filename = null;
 837        }
 838        if (filename == null) {
 839            final List<String> segments = uri.getPathSegments();
 840            if (segments.size() > 0) {
 841                filename = segments.get(segments.size() - 1);
 842            }
 843        }
 844        final int pos = filename == null ? -1 : filename.lastIndexOf('.');
 845        return pos > 0 ? filename.substring(pos + 1) : null;
 846    }
 847
 848    private void copyImageToPrivateStorage(File file, Uri image, int sampleSize)
 849            throws FileCopyException, ImageCompressionException {
 850        final File parent = file.getParentFile();
 851        if (parent != null && parent.mkdirs()) {
 852            Log.d(Config.LOGTAG, "created parent directory");
 853        }
 854        InputStream is = null;
 855        OutputStream os = null;
 856        try {
 857            if (!file.exists() && !file.createNewFile()) {
 858                throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 859            }
 860            is = mXmppConnectionService.getContentResolver().openInputStream(image);
 861            if (is == null) {
 862                throw new FileCopyException(R.string.error_not_an_image_file);
 863            }
 864            final Bitmap originalBitmap;
 865            final BitmapFactory.Options options = new BitmapFactory.Options();
 866            final int inSampleSize = (int) Math.pow(2, sampleSize);
 867            Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
 868            options.inSampleSize = inSampleSize;
 869            originalBitmap = BitmapFactory.decodeStream(is, null, options);
 870            is.close();
 871            if (originalBitmap == null) {
 872                throw new ImageCompressionException("Source file was not an image");
 873            }
 874            if (!"image/jpeg".equals(options.outMimeType) && hasAlpha(originalBitmap)) {
 875                originalBitmap.recycle();
 876                throw new ImageCompressionException("Source file had alpha channel");
 877            }
 878            Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
 879            final int rotation = getRotation(image);
 880            scaledBitmap = rotate(scaledBitmap, rotation);
 881            boolean targetSizeReached = false;
 882            int quality = Config.IMAGE_QUALITY;
 883            final int imageMaxSize =
 884                    mXmppConnectionService
 885                            .getResources()
 886                            .getInteger(R.integer.auto_accept_filesize);
 887            while (!targetSizeReached) {
 888                os = new FileOutputStream(file);
 889                Log.d(Config.LOGTAG, "compressing image with quality " + quality);
 890                boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
 891                if (!success) {
 892                    throw new FileCopyException(R.string.error_compressing_image);
 893                }
 894                os.flush();
 895                final long fileSize = file.length();
 896                Log.d(Config.LOGTAG, "achieved file size of " + fileSize);
 897                targetSizeReached = fileSize <= imageMaxSize || quality <= 50;
 898                quality -= 5;
 899            }
 900            scaledBitmap.recycle();
 901        } catch (final FileNotFoundException e) {
 902            cleanup(file);
 903            throw new FileCopyException(R.string.error_file_not_found);
 904        } catch (final IOException e) {
 905            cleanup(file);
 906            throw new FileCopyException(R.string.error_io_exception);
 907        } catch (SecurityException e) {
 908            cleanup(file);
 909            throw new FileCopyException(R.string.error_security_exception_during_image_copy);
 910        } catch (final OutOfMemoryError e) {
 911            ++sampleSize;
 912            if (sampleSize <= 3) {
 913                copyImageToPrivateStorage(file, image, sampleSize);
 914            } else {
 915                throw new FileCopyException(R.string.error_out_of_memory);
 916            }
 917        } finally {
 918            close(os);
 919            close(is);
 920        }
 921    }
 922
 923    private static void cleanup(final File file) {
 924        try {
 925            file.delete();
 926        } catch (Exception e) {
 927
 928        }
 929    }
 930
 931    public void copyImageToPrivateStorage(File file, Uri image)
 932            throws FileCopyException, ImageCompressionException {
 933        Log.d(
 934                Config.LOGTAG,
 935                "copy image ("
 936                        + image.toString()
 937                        + ") to private storage "
 938                        + file.getAbsolutePath());
 939        copyImageToPrivateStorage(file, image, 0);
 940    }
 941
 942    public void copyImageToPrivateStorage(Message message, Uri image)
 943            throws FileCopyException, ImageCompressionException {
 944        final String filename;
 945        switch (Config.IMAGE_FORMAT) {
 946            case JPEG:
 947                filename = String.format("%s.%s", message.getUuid(), "jpg");
 948                break;
 949            case PNG:
 950                filename = String.format("%s.%s", message.getUuid(), "png");
 951                break;
 952            case WEBP:
 953                filename = String.format("%s.%s", message.getUuid(), "webp");
 954                break;
 955            default:
 956                throw new IllegalStateException("Unknown image format");
 957        }
 958        setupRelativeFilePath(message, filename);
 959        final File tmp = getFile(message);
 960        copyImageToPrivateStorage(tmp, image);
 961        final String extension = MimeUtils.extractRelevantExtension(filename);
 962        try {
 963            setupRelativeFilePath(message, new FileInputStream(tmp), extension);
 964        } catch (final FileNotFoundException e) {
 965            throw new FileCopyException(R.string.error_file_not_found);
 966        } catch (final IOException e) {
 967            throw new FileCopyException(R.string.error_io_exception);
 968        } catch (final XmppConnectionService.BlockedMediaException e) {
 969            tmp.delete();
 970            message.setRelativeFilePath(null);
 971            message.setDeleted(true);
 972            return;
 973        }
 974        tmp.renameTo(getFile(message));
 975        updateFileParams(message, null, false);
 976    }
 977
 978    public void setupRelativeFilePath(final Message message, final Uri uri, final String extension) throws FileCopyException, XmppConnectionService.BlockedMediaException {
 979        try {
 980            setupRelativeFilePath(message, openInputStream(uri), extension);
 981        } catch (final FileNotFoundException e) {
 982            throw new FileCopyException(R.string.error_file_not_found);
 983        } catch (final IOException e) {
 984            throw new FileCopyException(R.string.error_io_exception);
 985        }
 986    }
 987
 988    public Cid[] calculateCids(final Uri uri) throws IOException {
 989        return calculateCids(mXmppConnectionService.getContentResolver().openInputStream(uri));
 990    }
 991
 992    public Cid[] calculateCids(final InputStream is) throws IOException {
 993        try {
 994            return CryptoHelper.cid(is, new String[]{"SHA-256", "SHA-1", "SHA-512"});
 995        } catch (final NoSuchAlgorithmException e) {
 996            throw new AssertionError(e);
 997        }
 998    }
 999
1000    public void setupRelativeFilePath(final Message message, final InputStream is, final String extension) throws IOException, XmppConnectionService.BlockedMediaException {
1001        message.setRelativeFilePath(getStorageLocation(is, extension).getAbsolutePath());
1002    }
1003
1004    public void setupRelativeFilePath(final Message message, final String filename) {
1005        final String extension = MimeUtils.extractRelevantExtension(filename);
1006        final String mime = MimeUtils.guessMimeTypeFromExtension(extension);
1007        setupRelativeFilePath(message, filename, mime);
1008    }
1009
1010    public File getStorageLocation(final InputStream is, final String extension) throws IOException, XmppConnectionService.BlockedMediaException {
1011        final String mime = MimeUtils.guessMimeTypeFromExtension(extension);
1012        Cid[] cids = calculateCids(is);
1013        String base = cids[0].toString();
1014
1015        File file = null;
1016        while (file == null || (file.exists() && !file.canRead())) {
1017            file = getStorageLocation(String.format("%s.%s", base, extension), mime);
1018            base += "_";
1019        }
1020        for (int i = 0; i < cids.length; i++) {
1021            mXmppConnectionService.saveCid(cids[i], file);
1022        }
1023        return file;
1024    }
1025
1026    public File getStorageLocation(final String filename, final String mime) {
1027        final File parentDirectory;
1028        if (Strings.isNullOrEmpty(mime)) {
1029            parentDirectory =
1030                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
1031        } else if (mime.startsWith("image/")) {
1032            parentDirectory =
1033                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
1034        } else if (mime.startsWith("video/")) {
1035            parentDirectory =
1036                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
1037        } else if (MediaAdapter.DOCUMENT_MIMES.contains(mime)) {
1038            parentDirectory =
1039                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
1040        } else {
1041            parentDirectory =
1042                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
1043        }
1044        final File appDirectory =
1045                new File(parentDirectory, mXmppConnectionService.getString(R.string.app_name));
1046        return new File(appDirectory, filename);
1047    }
1048
1049    public static boolean inConversationsDirectory(final Context context, String path) {
1050        final File fileDirectory = new File(path).getParentFile();
1051        for (final String type : STORAGE_TYPES) {
1052            final File typeDirectory =
1053                    new File(
1054                            Environment.getExternalStoragePublicDirectory(type),
1055                            context.getString(R.string.app_name));
1056            if (typeDirectory.equals(fileDirectory)) {
1057                return true;
1058            }
1059        }
1060        return false;
1061    }
1062
1063    public void setupRelativeFilePath(
1064            final Message message, final String filename, final String mime) {
1065        final File file = getStorageLocation(filename, mime);
1066        message.setRelativeFilePath(file.getAbsolutePath());
1067    }
1068
1069    public boolean unusualBounds(final Uri image) {
1070        try {
1071            final BitmapFactory.Options options = new BitmapFactory.Options();
1072            options.inJustDecodeBounds = true;
1073            final InputStream inputStream =
1074                    mXmppConnectionService.getContentResolver().openInputStream(image);
1075            BitmapFactory.decodeStream(inputStream, null, options);
1076            close(inputStream);
1077            float ratio = (float) options.outHeight / options.outWidth;
1078            return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
1079        } catch (final Exception e) {
1080            Log.w(Config.LOGTAG, "unable to detect image bounds", e);
1081            return false;
1082        }
1083    }
1084
1085    private int getRotation(final File file) {
1086        try (final InputStream inputStream = new FileInputStream(file)) {
1087            return getRotation(inputStream);
1088        } catch (Exception e) {
1089            return 0;
1090        }
1091    }
1092
1093    private int getRotation(final Uri image) {
1094        try (final InputStream is =
1095                mXmppConnectionService.getContentResolver().openInputStream(image)) {
1096            return is == null ? 0 : getRotation(is);
1097        } catch (final Exception e) {
1098            return 0;
1099        }
1100    }
1101
1102    private static int getRotation(final InputStream inputStream) throws IOException {
1103        final ExifInterface exif = new ExifInterface(inputStream);
1104        final int orientation =
1105                exif.getAttributeInt(
1106                        ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
1107        switch (orientation) {
1108            case ExifInterface.ORIENTATION_ROTATE_180:
1109                return 180;
1110            case ExifInterface.ORIENTATION_ROTATE_90:
1111                return 90;
1112            case ExifInterface.ORIENTATION_ROTATE_270:
1113                return 270;
1114            default:
1115                return 0;
1116        }
1117    }
1118
1119    public BitmapDrawable getFallbackThumbnail(final Message message, int size, boolean cacheOnly) {
1120        List<Element> thumbs = message.getFileParams() != null ? message.getFileParams().getThumbnails() : null;
1121        if (thumbs != null && !thumbs.isEmpty()) {
1122            for (Element thumb : thumbs) {
1123                Uri uri = Uri.parse(thumb.getAttribute("uri"));
1124                if (uri.getScheme().equals("data")) {
1125                    String[] parts = uri.getSchemeSpecificPart().split(",", 2);
1126
1127                    final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
1128                    BitmapDrawable cached = (BitmapDrawable) cache.get(parts[1]);
1129                    if (cached != null || cacheOnly) return cached;
1130
1131                    byte[] data;
1132                    if (Arrays.asList(parts[0].split(";")).contains("base64")) {
1133                        String[] parts2 = parts[0].split(";", 2);
1134                        parts[0] = parts2[0];
1135                        data = Base64.decode(parts[1], 0);
1136                    } else {
1137                        try {
1138                            data = parts[1].getBytes("UTF-8");
1139                        } catch (final IOException e) {
1140                            data = new byte[0];
1141                        }
1142                    }
1143
1144                    if (parts[0].equals("image/blurhash")) {
1145                        int width = message.getFileParams().width;
1146                        if (width < 1 && thumb.getAttribute("width") != null) width = Integer.parseInt(thumb.getAttribute("width"));
1147                        if (width < 1) width = 1920;
1148
1149                        int height = message.getFileParams().height;
1150                        if (height < 1 && thumb.getAttribute("height") != null) height = Integer.parseInt(thumb.getAttribute("height"));
1151                        if (height < 1) height = 1080;
1152                        Rect r = rectForSize(width, height, size);
1153
1154                        Bitmap blurhash = BlurHashDecoder.INSTANCE.decode(parts[1], r.width(), r.height(), 1.0f, false);
1155                        if (blurhash != null) {
1156                            cached = new BitmapDrawable(blurhash);
1157                            if (parts[1] != null && cached != null) cache.put(parts[1], cached);
1158                            return cached;
1159                        }
1160                    } else if (parts[0].equals("image/thumbhash")) {
1161                        ThumbHash.Image image;
1162                        try {
1163                            image = ThumbHash.thumbHashToRGBA(data);
1164                        } catch (final Exception e) {
1165                            continue;
1166                        }
1167                        int[] pixels = new int[image.width * image.height];
1168                        for (int i = 0; i < pixels.length; i++) {
1169                            pixels[i] = Color.argb(image.rgba[(i*4)+3] & 0xff, image.rgba[i*4] & 0xff, image.rgba[(i*4)+1] & 0xff, image.rgba[(i*4)+2] & 0xff);
1170                        }
1171                        cached = new BitmapDrawable(Bitmap.createBitmap(pixels, image.width, image.height, Bitmap.Config.ARGB_8888));
1172                        if (parts[1] != null && cached != null) cache.put(parts[1], cached);
1173                        return cached;
1174                    }
1175                }
1176            }
1177         }
1178
1179        return null;
1180    }
1181
1182    public Drawable getThumbnail(Message message, Resources res, int size, boolean cacheOnly) throws IOException {
1183        final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
1184        DownloadableFile file = getFile(message);
1185        Drawable thumbnail = cache.get(file.getAbsolutePath());
1186        if (thumbnail != null) return thumbnail;
1187
1188        if ((thumbnail == null) && (!cacheOnly)) {
1189            synchronized (THUMBNAIL_LOCK) {
1190                List<Element> thumbs = message.getFileParams() != null ? message.getFileParams().getThumbnails() : null;
1191                if (thumbs != null && !thumbs.isEmpty()) {
1192                    for (Element thumb : thumbs) {
1193                        Uri uri = Uri.parse(thumb.getAttribute("uri"));
1194                        if (uri.getScheme().equals("data")) {
1195                            if (android.os.Build.VERSION.SDK_INT < 28) continue;
1196                            String[] parts = uri.getSchemeSpecificPart().split(",", 2);
1197
1198                            byte[] data;
1199                            if (Arrays.asList(parts[0].split(";")).contains("base64")) {
1200                                String[] parts2 = parts[0].split(";", 2);
1201                                parts[0] = parts2[0];
1202                                data = Base64.decode(parts[1], 0);
1203                            } else {
1204                                data = parts[1].getBytes("UTF-8");
1205                            }
1206
1207                            if (parts[0].equals("image/blurhash")) continue; // blurhash only for fallback
1208                            if (parts[0].equals("image/thumbhash")) continue; // thumbhash only for fallback
1209
1210                            ImageDecoder.Source source = ImageDecoder.createSource(ByteBuffer.wrap(data));
1211                            thumbnail = ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1212                                int w = info.getSize().getWidth();
1213                                int h = info.getSize().getHeight();
1214                                Rect r = rectForSize(w, h, size);
1215                                decoder.setTargetSize(r.width(), r.height());
1216                            });
1217
1218                            if (thumbnail != null && file.getAbsolutePath() != null) {
1219                                cache.put(file.getAbsolutePath(), thumbnail);
1220                                return thumbnail;
1221                            }
1222                        } else if (uri.getScheme().equals("cid")) {
1223                            Cid cid = BobTransfer.cid(uri);
1224                            if (cid == null) continue;
1225                            DownloadableFile f = mXmppConnectionService.getFileForCid(cid);
1226                            if (f != null && f.canRead()) {
1227                                return getThumbnail(f, res, size, cacheOnly);
1228                            }
1229                        }
1230                    }
1231                }
1232            }
1233        }
1234
1235        return getThumbnail(file, res, size, cacheOnly);
1236    }
1237
1238    public Drawable getThumbnail(DownloadableFile file, Resources res, int size, boolean cacheOnly) throws IOException {
1239        return getThumbnail(file, res, size, cacheOnly, file.getAbsolutePath());
1240    }
1241
1242    public Drawable getThumbnail(DownloadableFile file, Resources res, int size, boolean cacheOnly, String cacheKey) throws IOException {
1243        final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
1244        Drawable thumbnail = cache.get(cacheKey);
1245        if ((thumbnail == null) && (!cacheOnly) && file.exists()) {
1246            synchronized (THUMBNAIL_LOCK) {
1247                thumbnail = cache.get(cacheKey);
1248                if (thumbnail != null) {
1249                    return thumbnail;
1250                }
1251                final String mime = file.getMimeType();
1252                if ("image/svg+xml".equals(mime)) {
1253                    thumbnail = getSVG(file, size);
1254                } else if ("application/pdf".equals(mime)) {
1255                    thumbnail = new BitmapDrawable(res, getPdfDocumentPreview(file, size));
1256                } else if (mime.startsWith("video/")) {
1257                    thumbnail = new BitmapDrawable(res, getVideoPreview(file, size));
1258                } else {
1259                    thumbnail = getImagePreview(file, res, size, mime);
1260                    if (thumbnail == null) {
1261                        throw new FileNotFoundException();
1262                    }
1263                }
1264                if (cacheKey != null && thumbnail != null) cache.put(cacheKey, thumbnail);
1265            }
1266        }
1267        return thumbnail;
1268    }
1269
1270    public Bitmap getThumbnailBitmap(Message message, Resources res, int size) throws IOException {
1271          final Drawable drawable = getThumbnail(message, res, size, false);
1272          if (drawable == null) return null;
1273          return drawDrawable(drawable);
1274    }
1275
1276    public Bitmap getThumbnailBitmap(DownloadableFile file, Resources res, int size, String cacheKey) throws IOException {
1277          final Drawable drawable = getThumbnail(file, res, size, false, cacheKey);
1278          if (drawable == null) return null;
1279          return drawDrawable(drawable);
1280    }
1281
1282    public static Rect rectForSize(int w, int h, int size) {
1283        int scalledW;
1284        int scalledH;
1285        if (w <= h) {
1286            scalledW = Math.max((int) (w / ((double) h / size)), 1);
1287            scalledH = size;
1288        } else {
1289            scalledW = size;
1290            scalledH = Math.max((int) (h / ((double) w / size)), 1);
1291        }
1292
1293        if (scalledW > w || scalledH > h) return new Rect(0, 0, w, h);
1294
1295        return new Rect(0, 0, scalledW, scalledH);
1296    }
1297
1298    private Drawable getImagePreview(File file, Resources res, int size, final String mime) throws IOException {
1299        if (android.os.Build.VERSION.SDK_INT >= 28) {
1300            ImageDecoder.Source source = ImageDecoder.createSource(file);
1301            return ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1302                int w = info.getSize().getWidth();
1303                int h = info.getSize().getHeight();
1304                Rect r = rectForSize(w, h, size);
1305                decoder.setTargetSize(r.width(), r.height());
1306            });
1307        } else {
1308            BitmapFactory.Options options = new BitmapFactory.Options();
1309            options.inSampleSize = calcSampleSize(file, size);
1310            Bitmap bitmap = null;
1311            try {
1312                bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1313            } catch (OutOfMemoryError e) {
1314                options.inSampleSize *= 2;
1315                bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1316            }
1317            if (bitmap == null) return null;
1318
1319            bitmap = resize(bitmap, size);
1320            bitmap = rotate(bitmap, getRotation(file));
1321            if (mime.equals("image/gif")) {
1322                Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
1323                drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
1324                bitmap.recycle();
1325                bitmap = withGifOverlay;
1326            }
1327            return new BitmapDrawable(res, bitmap);
1328        }
1329    }
1330
1331    public static Bitmap drawDrawable(Drawable drawable) {
1332        if (drawable == null) return null;
1333
1334        Bitmap bitmap = null;
1335
1336        if (drawable instanceof BitmapDrawable) {
1337            bitmap = ((BitmapDrawable) drawable).getBitmap();
1338            if (bitmap != null) return bitmap;
1339        }
1340
1341        Rect bounds = drawable.getBounds();
1342        int width = drawable.getIntrinsicWidth();
1343        if (width < 1) width = bounds == null || bounds.right < 1 ? 256 : bounds.right;
1344        int height = drawable.getIntrinsicHeight();
1345        if (height < 1) height = bounds == null || bounds.bottom < 1 ? 256 : bounds.bottom;
1346
1347        if (width < 1) {
1348            Log.w(Config.LOGTAG, "Drawable with no width: " + drawable);
1349            width = 48;
1350        }
1351        if (height < 1) {
1352            Log.w(Config.LOGTAG, "Drawable with no height: " + drawable);
1353            height = 48;
1354        }
1355
1356        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1357        Canvas canvas = new Canvas(bitmap);
1358        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1359        drawable.draw(canvas);
1360        return bitmap;
1361    }
1362
1363    private void drawOverlay(Bitmap bitmap, int resource, float factor) {
1364        Bitmap overlay =
1365                BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
1366        Canvas canvas = new Canvas(bitmap);
1367        float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
1368        Log.d(
1369                Config.LOGTAG,
1370                "target size overlay: "
1371                        + targetSize
1372                        + " overlay bitmap size was "
1373                        + overlay.getHeight());
1374        float left = (canvas.getWidth() - targetSize) / 2.0f;
1375        float top = (canvas.getHeight() - targetSize) / 2.0f;
1376        RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
1377        canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
1378    }
1379
1380    /** https://stackoverflow.com/a/3943023/210897 */
1381    private boolean paintOverlayBlack(final Bitmap bitmap) {
1382        final int h = bitmap.getHeight();
1383        final int w = bitmap.getWidth();
1384        int record = 0;
1385        for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
1386            for (int x = Math.round(w * IGNORE_PADDING);
1387                    x < w - Math.round(w * IGNORE_PADDING);
1388                    ++x) {
1389                int pixel = bitmap.getPixel(x, y);
1390                if ((Color.red(pixel) * 0.299
1391                                + Color.green(pixel) * 0.587
1392                                + Color.blue(pixel) * 0.114)
1393                        > 186) {
1394                    --record;
1395                } else {
1396                    ++record;
1397                }
1398            }
1399        }
1400        return record < 0;
1401    }
1402
1403    private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
1404        final int h = bitmap.getHeight();
1405        final int w = bitmap.getWidth();
1406        int white = 0;
1407        for (int y = 0; y < h; ++y) {
1408            for (int x = 0; x < w; ++x) {
1409                int pixel = bitmap.getPixel(x, y);
1410                if ((Color.red(pixel) * 0.299
1411                                + Color.green(pixel) * 0.587
1412                                + Color.blue(pixel) * 0.114)
1413                        > 186) {
1414                    white++;
1415                }
1416            }
1417        }
1418        return white > (h * w * 0.4f);
1419    }
1420
1421    private Bitmap cropCenterSquareVideo(Uri uri, int size) {
1422        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1423        Bitmap frame;
1424        try {
1425            metadataRetriever.setDataSource(mXmppConnectionService, uri);
1426            frame = metadataRetriever.getFrameAtTime(0);
1427            metadataRetriever.release();
1428            return cropCenterSquare(frame, size);
1429        } catch (Exception e) {
1430            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1431            frame.eraseColor(0xff000000);
1432            return frame;
1433        }
1434    }
1435
1436    private Bitmap getVideoPreview(final File file, final int size) {
1437        final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1438        Bitmap frame;
1439        try {
1440            metadataRetriever.setDataSource(file.getAbsolutePath());
1441            frame = metadataRetriever.getFrameAtTime(0);
1442            metadataRetriever.release();
1443            frame = resize(frame, size);
1444        } catch (IOException | RuntimeException e) {
1445            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1446            frame.eraseColor(0xff000000);
1447        }
1448        drawOverlay(
1449                frame,
1450                paintOverlayBlack(frame)
1451                        ? R.drawable.play_video_black
1452                        : R.drawable.play_video_white,
1453                0.75f);
1454        return frame;
1455    }
1456
1457    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1458    private Bitmap getPdfDocumentPreview(final File file, final int size) {
1459        try {
1460            final ParcelFileDescriptor fileDescriptor =
1461                    ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1462            final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
1463            drawOverlay(
1464                    rendered,
1465                    paintOverlayBlackPdf(rendered)
1466                            ? R.drawable.open_pdf_black
1467                            : R.drawable.open_pdf_white,
1468                    0.75f);
1469            return rendered;
1470        } catch (final IOException | SecurityException e) {
1471            Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
1472            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1473            placeholder.eraseColor(0xff000000);
1474            return placeholder;
1475        }
1476    }
1477
1478    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1479    private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
1480        try {
1481            ParcelFileDescriptor fileDescriptor =
1482                    mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
1483            final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1484            return cropCenterSquare(bitmap, size);
1485        } catch (Exception e) {
1486            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1487            placeholder.eraseColor(0xff000000);
1488            return placeholder;
1489        }
1490    }
1491
1492    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1493    private Bitmap renderPdfDocument(
1494            ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1495        final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1496        final PdfRenderer.Page page = pdfRenderer.openPage(0);
1497        final Dimensions dimensions =
1498                scalePdfDimensions(
1499                        new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1500        final Bitmap rendered =
1501                Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1502        rendered.eraseColor(0xffffffff);
1503        page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1504        page.close();
1505        pdfRenderer.close();
1506        fileDescriptor.close();
1507        return rendered;
1508    }
1509
1510    public Uri getTakePhotoUri() {
1511        final String filename =
1512                String.format("IMG_%s.%s", IMAGE_DATE_FORMAT.format(new Date()), "jpg");
1513        final File directory;
1514        if (Config.ONLY_INTERNAL_STORAGE) {
1515            directory = new File(mXmppConnectionService.getCacheDir(), "Camera");
1516        } else {
1517            directory =
1518                    new File(
1519                            Environment.getExternalStoragePublicDirectory(
1520                                    Environment.DIRECTORY_DCIM),
1521                            "Camera");
1522        }
1523        final File file = new File(directory, filename);
1524        file.getParentFile().mkdirs();
1525        return getUriForFile(mXmppConnectionService, file);
1526    }
1527
1528    public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
1529
1530        final Pair<Avatar,Boolean> uncompressAvatar = getUncompressedAvatar(image);
1531        if (uncompressAvatar != null && uncompressAvatar.first != null &&
1532                (uncompressAvatar.first.image.length() <= Config.AVATAR_CHAR_LIMIT || uncompressAvatar.second)) {
1533            return uncompressAvatar.first;
1534        }
1535        if (uncompressAvatar != null && uncompressAvatar.first != null) {
1536            Log.d(
1537                    Config.LOGTAG,
1538                    "uncompressed avatar exceeded char limit by "
1539                            + (uncompressAvatar.first.image.length() - Config.AVATAR_CHAR_LIMIT));
1540        }
1541
1542        Bitmap bm = cropCenterSquare(image, size);
1543        if (bm == null) {
1544            return null;
1545        }
1546        if (hasAlpha(bm)) {
1547            Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
1548            bm.recycle();
1549            bm = cropCenterSquare(image, 96);
1550            return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
1551        }
1552        return getPepAvatar(bm, format, 100);
1553    }
1554
1555    private Pair<Avatar,Boolean> getUncompressedAvatar(Uri uri) {
1556        try {
1557            if (android.os.Build.VERSION.SDK_INT >= 28) {
1558                ImageDecoder.Source source = ImageDecoder.createSource(mXmppConnectionService.getContentResolver(), uri);
1559                int[] size = new int[] { 0, 0 };
1560                boolean[] animated = new boolean[] { false };
1561                String[] mimeType = new String[] { null };
1562                Drawable drawable = ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1563                    mimeType[0] = info.getMimeType();
1564                    animated[0] = info.isAnimated();
1565                    size[0] = info.getSize().getWidth();
1566                    size[1] = info.getSize().getHeight();
1567                });
1568
1569                if (animated[0]) {
1570                    Avatar avatar = getPepAvatar(uri, size[0], size[1], mimeType[0]);
1571                    if (avatar != null) return new Pair(avatar, true);
1572                }
1573
1574                return new Pair(getPepAvatar(drawDrawable(drawable), Bitmap.CompressFormat.PNG, 100), false);
1575            } else {
1576                Bitmap bitmap =
1577                    BitmapFactory.decodeStream(
1578                            mXmppConnectionService.getContentResolver().openInputStream(uri));
1579                return new Pair(getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100), false);
1580            }
1581        } catch (Exception e) {
1582            try {
1583                final SVG svg = SVG.getFromInputStream(mXmppConnectionService.getContentResolver().openInputStream(uri));
1584                return new Pair(getPepAvatar(uri, (int) svg.getDocumentWidth(), (int) svg.getDocumentHeight(), "image/svg+xml"), true);
1585            } catch (Exception e2) {
1586                return null;
1587            }
1588        }
1589    }
1590
1591    private Avatar getPepAvatar(Uri uri, int width, int height, final String mimeType) throws IOException, NoSuchAlgorithmException {
1592        AssetFileDescriptor fd = mXmppConnectionService.getContentResolver().openAssetFileDescriptor(uri, "r");
1593        if (fd.getLength() > 100000) return null; // Too big to use raw file
1594
1595        ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1596        Base64OutputStream mBase64OutputStream =
1597                new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1598        MessageDigest digest = MessageDigest.getInstance("SHA-1");
1599        DigestOutputStream mDigestOutputStream =
1600                new DigestOutputStream(mBase64OutputStream, digest);
1601
1602        ByteStreams.copy(fd.createInputStream(), mDigestOutputStream);
1603        mDigestOutputStream.flush();
1604        mDigestOutputStream.close();
1605
1606        final Avatar avatar = new Avatar();
1607        avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1608        avatar.image = new String(mByteArrayOutputStream.toByteArray());
1609        avatar.type = mimeType;
1610        avatar.width = width;
1611        avatar.height = height;
1612        return avatar;
1613    }
1614
1615    private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1616        try {
1617            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1618            Base64OutputStream mBase64OutputStream =
1619                    new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1620            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1621            DigestOutputStream mDigestOutputStream =
1622                    new DigestOutputStream(mBase64OutputStream, digest);
1623            if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1624                return null;
1625            }
1626            mDigestOutputStream.flush();
1627            mDigestOutputStream.close();
1628            long chars = mByteArrayOutputStream.size();
1629            if (format != Bitmap.CompressFormat.PNG
1630                    && quality >= 50
1631                    && chars >= Config.AVATAR_CHAR_LIMIT) {
1632                int q = quality - 2;
1633                Log.d(
1634                        Config.LOGTAG,
1635                        "avatar char length was " + chars + " reducing quality to " + q);
1636                return getPepAvatar(bitmap, format, q);
1637            }
1638            Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1639            final Avatar avatar = new Avatar();
1640            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1641            avatar.image = new String(mByteArrayOutputStream.toByteArray());
1642            if (format.equals(Bitmap.CompressFormat.WEBP)) {
1643                avatar.type = "image/webp";
1644            } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1645                avatar.type = "image/jpeg";
1646            } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1647                avatar.type = "image/png";
1648            }
1649            avatar.width = bitmap.getWidth();
1650            avatar.height = bitmap.getHeight();
1651            return avatar;
1652        } catch (OutOfMemoryError e) {
1653            Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1654            return null;
1655        } catch (Exception e) {
1656            return null;
1657        }
1658    }
1659
1660    public Avatar getStoredPepAvatar(String hash) {
1661        if (hash == null) {
1662            return null;
1663        }
1664        Avatar avatar = new Avatar();
1665        final File file = getAvatarFile(hash);
1666        FileInputStream is = null;
1667        try {
1668            avatar.size = file.length();
1669            BitmapFactory.Options options = new BitmapFactory.Options();
1670            options.inJustDecodeBounds = true;
1671            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1672            is = new FileInputStream(file);
1673            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1674            Base64OutputStream mBase64OutputStream =
1675                    new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1676            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1677            DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1678            byte[] buffer = new byte[4096];
1679            int length;
1680            while ((length = is.read(buffer)) > 0) {
1681                os.write(buffer, 0, length);
1682            }
1683            os.flush();
1684            os.close();
1685            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1686            avatar.image = new String(mByteArrayOutputStream.toByteArray());
1687            avatar.height = options.outHeight;
1688            avatar.width = options.outWidth;
1689            avatar.type = options.outMimeType;
1690            return avatar;
1691        } catch (NoSuchAlgorithmException | IOException e) {
1692            return null;
1693        } finally {
1694            close(is);
1695        }
1696    }
1697
1698    public boolean isAvatarCached(Avatar avatar) {
1699        final File file = getAvatarFile(avatar.getFilename());
1700        return file.exists();
1701    }
1702
1703    public boolean save(final Avatar avatar) {
1704        File file;
1705        if (isAvatarCached(avatar)) {
1706            file = getAvatarFile(avatar.getFilename());
1707            avatar.size = file.length();
1708        } else {
1709            file =
1710                    new File(
1711                            mXmppConnectionService.getCacheDir().getAbsolutePath()
1712                                    + "/"
1713                                    + UUID.randomUUID().toString());
1714            if (file.getParentFile().mkdirs()) {
1715                Log.d(Config.LOGTAG, "created cache directory");
1716            }
1717            OutputStream os = null;
1718            try {
1719                if (!file.createNewFile()) {
1720                    Log.d(
1721                            Config.LOGTAG,
1722                            "unable to create temporary file " + file.getAbsolutePath());
1723                }
1724                os = new FileOutputStream(file);
1725                MessageDigest digest = MessageDigest.getInstance("SHA-1");
1726                digest.reset();
1727                DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1728                final byte[] bytes = avatar.getImageAsBytes();
1729                mDigestOutputStream.write(bytes);
1730                mDigestOutputStream.flush();
1731                mDigestOutputStream.close();
1732                String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1733                if (sha1sum.equals(avatar.sha1sum)) {
1734                    final File outputFile = getAvatarFile(avatar.getFilename());
1735                    if (outputFile.getParentFile().mkdirs()) {
1736                        Log.d(Config.LOGTAG, "created avatar directory");
1737                    }
1738                    final File avatarFile = getAvatarFile(avatar.getFilename());
1739                    if (!file.renameTo(avatarFile)) {
1740                        Log.d(
1741                                Config.LOGTAG,
1742                                "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1743                        return false;
1744                    }
1745                } else {
1746                    Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1747                    if (!file.delete()) {
1748                        Log.d(Config.LOGTAG, "unable to delete temporary file");
1749                    }
1750                    return false;
1751                }
1752                avatar.size = bytes.length;
1753            } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1754                return false;
1755            } finally {
1756                close(os);
1757            }
1758        }
1759        return true;
1760    }
1761
1762    public void deleteHistoricAvatarPath() {
1763        delete(getHistoricAvatarPath());
1764    }
1765
1766    private void delete(final File file) {
1767        if (file.isDirectory()) {
1768            final File[] files = file.listFiles();
1769            if (files != null) {
1770                for (final File f : files) {
1771                    delete(f);
1772                }
1773            }
1774        }
1775        if (file.delete()) {
1776            Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1777        }
1778    }
1779
1780    private File getHistoricAvatarPath() {
1781        return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1782    }
1783
1784    public File getAvatarFile(String avatar) {
1785        return new File(mXmppConnectionService.getCacheDir(), "/avatars/" + avatar);
1786    }
1787
1788    public Uri getAvatarUri(String avatar) {
1789        return Uri.fromFile(getAvatarFile(avatar));
1790    }
1791
1792    public Drawable cropCenterSquareDrawable(Uri image, int size) {
1793        if (android.os.Build.VERSION.SDK_INT >= 28) {
1794            try {
1795                ImageDecoder.Source source = ImageDecoder.createSource(mXmppConnectionService.getContentResolver(), image);
1796                return ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1797                    int w = info.getSize().getWidth();
1798                    int h = info.getSize().getHeight();
1799                    Rect r = rectForSize(w, h, size);
1800                    decoder.setTargetSize(r.width(), r.height());
1801
1802                    int newSize = Math.min(r.width(), r.height());
1803                    int left = (r.width() - newSize) / 2;
1804                    int top = (r.height() - newSize) / 2;
1805                    decoder.setCrop(new Rect(left, top, left + newSize, top + newSize));
1806                });
1807            } catch (final IOException e) {
1808                return getSVGSquare(image, size);
1809            }
1810        } else {
1811            Bitmap bitmap = cropCenterSquare(image, size);
1812            return bitmap == null ? null : new BitmapDrawable(bitmap);
1813        }
1814    }
1815
1816    public Bitmap cropCenterSquare(Uri image, int size) {
1817        if (image == null) {
1818            return null;
1819        }
1820        InputStream is = null;
1821        try {
1822            BitmapFactory.Options options = new BitmapFactory.Options();
1823            options.inSampleSize = calcSampleSize(image, size);
1824            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1825            if (is == null) {
1826                return null;
1827            }
1828            Bitmap input = BitmapFactory.decodeStream(is, null, options);
1829            if (input == null) {
1830                return null;
1831            } else {
1832                input = rotate(input, getRotation(image));
1833                return cropCenterSquare(input, size);
1834            }
1835        } catch (FileNotFoundException | SecurityException e) {
1836            Log.d(Config.LOGTAG, "unable to open file " + image.toString(), e);
1837            return null;
1838        } finally {
1839            close(is);
1840        }
1841    }
1842
1843    public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1844        if (image == null) {
1845            return null;
1846        }
1847        InputStream is = null;
1848        try {
1849            BitmapFactory.Options options = new BitmapFactory.Options();
1850            options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1851            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1852            if (is == null) {
1853                return null;
1854            }
1855            Bitmap source = BitmapFactory.decodeStream(is, null, options);
1856            if (source == null) {
1857                return null;
1858            }
1859            int sourceWidth = source.getWidth();
1860            int sourceHeight = source.getHeight();
1861            float xScale = (float) newWidth / sourceWidth;
1862            float yScale = (float) newHeight / sourceHeight;
1863            float scale = Math.max(xScale, yScale);
1864            float scaledWidth = scale * sourceWidth;
1865            float scaledHeight = scale * sourceHeight;
1866            float left = (newWidth - scaledWidth) / 2;
1867            float top = (newHeight - scaledHeight) / 2;
1868
1869            RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1870            Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1871            Canvas canvas = new Canvas(dest);
1872            canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1873            if (source.isRecycled()) {
1874                source.recycle();
1875            }
1876            return dest;
1877        } catch (SecurityException e) {
1878            return null; // android 6.0 with revoked permissions for example
1879        } catch (FileNotFoundException e) {
1880            return null;
1881        } finally {
1882            close(is);
1883        }
1884    }
1885
1886    public Bitmap cropCenterSquare(Bitmap input, int size) {
1887        int w = input.getWidth();
1888        int h = input.getHeight();
1889
1890        float scale = Math.max((float) size / h, (float) size / w);
1891
1892        float outWidth = scale * w;
1893        float outHeight = scale * h;
1894        float left = (size - outWidth) / 2;
1895        float top = (size - outHeight) / 2;
1896        RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1897
1898        Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1899        Canvas canvas = new Canvas(output);
1900        canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1901        if (!input.isRecycled()) {
1902            input.recycle();
1903        }
1904        return output;
1905    }
1906
1907    private int calcSampleSize(Uri image, int size)
1908            throws FileNotFoundException, SecurityException {
1909        final BitmapFactory.Options options = new BitmapFactory.Options();
1910        options.inJustDecodeBounds = true;
1911        final InputStream inputStream =
1912                mXmppConnectionService.getContentResolver().openInputStream(image);
1913        BitmapFactory.decodeStream(inputStream, null, options);
1914        close(inputStream);
1915        return calcSampleSize(options, size);
1916    }
1917
1918    public void updateFileParams(Message message) {
1919        updateFileParams(message, null);
1920    }
1921
1922    public void updateFileParams(final Message message, final String url) {
1923        updateFileParams(message, url, true);
1924    }
1925
1926    public void updateFileParams(final Message message, String url, boolean updateCids) {
1927        final boolean encrypted =
1928                message.getEncryption() == Message.ENCRYPTION_PGP
1929                        || message.getEncryption() == Message.ENCRYPTION_DECRYPTED;
1930        final DownloadableFile file = getFile(message);
1931        final String mime = file.getMimeType();
1932        final boolean privateMessage = message.isPrivateMessage();
1933        final boolean image =
1934                message.getType() == Message.TYPE_IMAGE
1935                        || (mime != null && mime.startsWith("image/"));
1936        Message.FileParams fileParams = message.getFileParams();
1937        if (fileParams == null) fileParams = new Message.FileParams();
1938        Cid[] cids = new Cid[0];
1939        try {
1940            cids = calculateCids(new FileInputStream(file));
1941            fileParams.setCids(List.of(cids));
1942        } catch (final IOException | NoSuchAlgorithmException e) { }
1943        if (url == null) {
1944            for (Cid cid : cids) {
1945                url = mXmppConnectionService.getUrlForCid(cid);
1946                if (url != null) {
1947                    fileParams.url = url;
1948                    break;
1949                }
1950            }
1951        } else {
1952            fileParams.url = url;
1953        }
1954        if (fileParams.getName() == null) fileParams.setName(file.getName());
1955        fileParams.setMediaType(mime);
1956        if (encrypted && !file.exists()) {
1957            Log.d(Config.LOGTAG, "skipping updateFileParams because file is encrypted");
1958            final DownloadableFile encryptedFile = getFile(message, false);
1959            if (encryptedFile.canRead()) fileParams.size = encryptedFile.getSize();
1960        } else {
1961            Log.d(Config.LOGTAG, "running updateFileParams");
1962            final boolean ambiguous = MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime);
1963            final boolean video = mime != null && mime.startsWith("video/");
1964            final boolean audio = mime != null && mime.startsWith("audio/");
1965            final boolean pdf = "application/pdf".equals(mime);
1966            if (file.canRead()) fileParams.size = file.getSize();
1967            if (ambiguous) {
1968                try {
1969                    final Dimensions dimensions = getVideoDimensions(file);
1970                    if (dimensions.valid()) {
1971                        Log.d(Config.LOGTAG, "ambiguous file " + mime + " is video");
1972                        fileParams.width = dimensions.width;
1973                        fileParams.height = dimensions.height;
1974                    } else {
1975                        Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1976                        fileParams.runtime = getMediaRuntime(file);
1977                    }
1978                } catch (final IOException | NotAVideoFile e) {
1979                    Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1980                    fileParams.runtime = getMediaRuntime(file);
1981                }
1982            } else if (image || video || pdf) {
1983                try {
1984                    final Dimensions dimensions;
1985                    if (video) {
1986                        dimensions = getVideoDimensions(file);
1987                    } else if (pdf) {
1988                        dimensions = getPdfDocumentDimensions(file);
1989                    } else if ("image/svg+xml".equals(mime)) {
1990                        SVG svg = SVG.getFromInputStream(new FileInputStream(file));
1991                        dimensions = new Dimensions((int) svg.getDocumentHeight(), (int) svg.getDocumentWidth());
1992                    } else {
1993                        dimensions = getImageDimensions(file);
1994                    }
1995                    if (dimensions.valid()) {
1996                        fileParams.width = dimensions.width;
1997                        fileParams.height = dimensions.height;
1998                    }
1999                } catch (final IOException | SVGParseException | NotAVideoFile notAVideoFile) {
2000                    Log.d(
2001                            Config.LOGTAG,
2002                            "file with mime type " + file.getMimeType() + " was not a video file");
2003                    // fall threw
2004                }
2005            } else if (audio) {
2006                fileParams.runtime = getMediaRuntime(file);
2007            }
2008            try {
2009                Bitmap thumb = getThumbnailBitmap(file, mXmppConnectionService.getResources(), 100, file.getAbsolutePath() + " x 100");
2010                if (thumb != null) {
2011                    int[] pixels = new int[thumb.getWidth() * thumb.getHeight()];
2012                    byte[] rgba = new byte[pixels.length * 4];
2013                    try {
2014                        thumb.getPixels(pixels, 0, thumb.getWidth(), 0, 0, thumb.getWidth(), thumb.getHeight());
2015                    } catch (final IllegalStateException e) {
2016                        Bitmap softThumb = thumb.copy(Bitmap.Config.ARGB_8888, false);
2017                        softThumb.getPixels(pixels, 0, thumb.getWidth(), 0, 0, thumb.getWidth(), thumb.getHeight());
2018                        softThumb.recycle();
2019                    }
2020                    for (int i = 0; i < pixels.length; i++) {
2021                        rgba[i*4] = (byte)((pixels[i] >> 16) & 0xff);
2022                        rgba[(i*4)+1] = (byte)((pixels[i] >> 8) & 0xff);
2023                        rgba[(i*4)+2] = (byte)(pixels[i] & 0xff);
2024                        rgba[(i*4)+3] = (byte)((pixels[i] >> 24) & 0xff);
2025                    }
2026                    fileParams.addThumbnail(thumb.getWidth(), thumb.getHeight(), "image/thumbhash", "data:image/thumbhash;base64," + Base64.encodeToString(ThumbHash.rgbaToThumbHash(thumb.getWidth(), thumb.getHeight(), rgba), Base64.NO_WRAP));
2027                }
2028            } catch (final IOException e) { }
2029        }
2030        message.setFileParams(fileParams);
2031        message.setDeleted(false);
2032        message.setType(
2033                privateMessage
2034                        ? Message.TYPE_PRIVATE_FILE
2035                        : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
2036
2037        if (updateCids) {
2038            try {
2039                for (int i = 0; i < cids.length; i++) {
2040                    mXmppConnectionService.saveCid(cids[i], file);
2041                }
2042            } catch (XmppConnectionService.BlockedMediaException e) { }
2043        }
2044    }
2045
2046    private int getMediaRuntime(final File file) {
2047        try {
2048            final MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
2049            mediaMetadataRetriever.setDataSource(file.toString());
2050            final String value =
2051                    mediaMetadataRetriever.extractMetadata(
2052                            MediaMetadataRetriever.METADATA_KEY_DURATION);
2053            if (Strings.isNullOrEmpty(value)) {
2054                return 0;
2055            }
2056            return Integer.parseInt(value);
2057        } catch (final Exception e) {
2058            return 0;
2059        }
2060    }
2061
2062    private Dimensions getImageDimensions(File file) {
2063        final BitmapFactory.Options options = new BitmapFactory.Options();
2064        options.inJustDecodeBounds = true;
2065        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
2066        final int rotation = getRotation(file);
2067        final boolean rotated = rotation == 90 || rotation == 270;
2068        final int imageHeight = rotated ? options.outWidth : options.outHeight;
2069        final int imageWidth = rotated ? options.outHeight : options.outWidth;
2070        return new Dimensions(imageHeight, imageWidth);
2071    }
2072
2073    private Dimensions getVideoDimensions(final File file) throws NotAVideoFile, IOException {
2074        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
2075        try {
2076            metadataRetriever.setDataSource(file.getAbsolutePath());
2077        } catch (RuntimeException e) {
2078            throw new NotAVideoFile(e);
2079        }
2080        return getVideoDimensions(metadataRetriever);
2081    }
2082
2083    private Dimensions getPdfDocumentDimensions(final File file) {
2084        final ParcelFileDescriptor fileDescriptor;
2085        try {
2086            fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
2087            if (fileDescriptor == null) {
2088                return new Dimensions(0, 0);
2089            }
2090        } catch (final FileNotFoundException e) {
2091            return new Dimensions(0, 0);
2092        }
2093        try {
2094            final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
2095            final PdfRenderer.Page page = pdfRenderer.openPage(0);
2096            final int height = page.getHeight();
2097            final int width = page.getWidth();
2098            page.close();
2099            pdfRenderer.close();
2100            return scalePdfDimensions(new Dimensions(height, width));
2101        } catch (final IOException | SecurityException e) {
2102            Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
2103            return new Dimensions(0, 0);
2104        }
2105    }
2106
2107    private Dimensions scalePdfDimensions(Dimensions in) {
2108        final DisplayMetrics displayMetrics =
2109                mXmppConnectionService.getResources().getDisplayMetrics();
2110        final int target = (int) (displayMetrics.density * 288);
2111        return scalePdfDimensions(in, target, true);
2112    }
2113
2114    private static Dimensions scalePdfDimensions(
2115            final Dimensions in, final int target, final boolean fit) {
2116        final int w, h;
2117        if (fit == (in.width <= in.height)) {
2118            w = Math.max((int) (in.width / ((double) in.height / target)), 1);
2119            h = target;
2120        } else {
2121            w = target;
2122            h = Math.max((int) (in.height / ((double) in.width / target)), 1);
2123        }
2124        return new Dimensions(h, w);
2125    }
2126
2127    public Drawable getAvatar(String avatar, int size) {
2128        if (avatar == null) {
2129            return null;
2130        }
2131
2132        if (android.os.Build.VERSION.SDK_INT >= 28) {
2133            try {
2134                ImageDecoder.Source source = ImageDecoder.createSource(getAvatarFile(avatar));
2135                return ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
2136                    int w = info.getSize().getWidth();
2137                    int h = info.getSize().getHeight();
2138                    Rect r = rectForSize(w, h, size);
2139                    decoder.setTargetSize(r.width(), r.height());
2140
2141                    int newSize = Math.min(r.width(), r.height());
2142                    int left = (r.width() - newSize) / 2;
2143                    int top = (r.height() - newSize) / 2;
2144                    decoder.setCrop(new Rect(left, top, left + newSize, top + newSize));
2145                });
2146            } catch (final IOException e) {
2147                return getSVGSquare(getAvatarUri(avatar), size);
2148            }
2149        } else {
2150            Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
2151            return bm == null ? null : new BitmapDrawable(bm);
2152        }
2153    }
2154
2155    public Drawable getSVGSquare(Uri uri, int size) {
2156        try {
2157            SVG svg = SVG.getFromInputStream(mXmppConnectionService.getContentResolver().openInputStream(uri));
2158            svg.setDocumentPreserveAspectRatio(com.caverock.androidsvg.PreserveAspectRatio.FULLSCREEN);
2159
2160            float w = svg.getDocumentWidth();
2161            float h = svg.getDocumentHeight();
2162            float scale = Math.max((float) size / h, (float) size / w);
2163            float outWidth = scale * w;
2164            float outHeight = scale * h;
2165            float left = (size - outWidth) / 2;
2166            float top = (size - outHeight) / 2;
2167            RectF target = new RectF(left, top, left + outWidth, top + outHeight);
2168            if (svg.getDocumentViewBox() == null) svg.setDocumentViewBox(0, 0, w, h);
2169            svg.setDocumentWidth("100%");
2170            svg.setDocumentHeight("100%");
2171
2172            Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
2173            Canvas canvas = new Canvas(output);
2174            svg.renderToCanvas(canvas, target);
2175
2176            return new SVGDrawable(output);
2177        } catch (final IOException | SVGParseException | IllegalArgumentException e) {
2178            Log.w(Config.LOGTAG, "Could not parse SVG: " + e);
2179            return null;
2180        }
2181    }
2182
2183    public Drawable getSVG(File file, int size) {
2184        try {
2185            SVG svg = SVG.getFromInputStream(new FileInputStream(file));
2186            return drawSVG(svg, size);
2187        } catch (final IOException | SVGParseException | IllegalArgumentException e) {
2188            Log.w(Config.LOGTAG, "Could not parse SVG: " + e);
2189            return null;
2190        }
2191    }
2192
2193    public Drawable drawSVG(SVG svg, int size) {
2194        try {
2195            svg.setDocumentPreserveAspectRatio(com.caverock.androidsvg.PreserveAspectRatio.LETTERBOX);
2196
2197            float w = svg.getDocumentWidth();
2198            float h = svg.getDocumentHeight();
2199            Rect r = rectForSize(w < 1 ? size : (int) w, h < 1 ? size : (int) h, size);
2200            if (svg.getDocumentViewBox() == null) svg.setDocumentViewBox(0, 0, w, h);
2201            svg.setDocumentWidth("100%");
2202            svg.setDocumentHeight("100%");
2203
2204            Bitmap output = Bitmap.createBitmap(r.width(), r.height(), Bitmap.Config.ARGB_8888);
2205            Canvas canvas = new Canvas(output);
2206            svg.renderToCanvas(canvas);
2207
2208            return new SVGDrawable(output);
2209        } catch (final SVGParseException e) {
2210            Log.w(Config.LOGTAG, "Could not parse SVG: " + e);
2211            return null;
2212        }
2213    }
2214
2215    private static class Dimensions {
2216        public final int width;
2217        public final int height;
2218
2219        Dimensions(int height, int width) {
2220            this.width = width;
2221            this.height = height;
2222        }
2223
2224        public int getMin() {
2225            return Math.min(width, height);
2226        }
2227
2228        public boolean valid() {
2229            return width > 0 && height > 0;
2230        }
2231    }
2232
2233    private static class NotAVideoFile extends Exception {
2234        public NotAVideoFile(Throwable t) {
2235            super(t);
2236        }
2237
2238        public NotAVideoFile() {
2239            super();
2240        }
2241    }
2242
2243    public static class ImageCompressionException extends Exception {
2244
2245        ImageCompressionException(String message) {
2246            super(message);
2247        }
2248    }
2249
2250    public static class FileCopyException extends Exception {
2251        private final int resId;
2252
2253        private FileCopyException(@StringRes int resId) {
2254            this.resId = resId;
2255        }
2256
2257        public @StringRes int getResId() {
2258            return resId;
2259        }
2260    }
2261
2262    public static class SVGDrawable extends BitmapDrawable {
2263        public SVGDrawable(Bitmap bm) { super(bm); }
2264    }
2265}