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