1package eu.siacs.conversations.persistance;
   2
   3import android.content.ContentResolver;
   4import android.content.Context;
   5import android.database.Cursor;
   6import android.graphics.Bitmap;
   7import android.graphics.BitmapFactory;
   8import android.graphics.Canvas;
   9import android.graphics.Color;
  10import android.graphics.Matrix;
  11import android.graphics.Paint;
  12import android.graphics.RectF;
  13import android.graphics.pdf.PdfRenderer;
  14import android.media.MediaMetadataRetriever;
  15import android.media.MediaScannerConnection;
  16import android.net.Uri;
  17import android.os.Build;
  18import android.os.Environment;
  19import android.os.ParcelFileDescriptor;
  20import android.provider.MediaStore;
  21import android.provider.OpenableColumns;
  22import android.system.Os;
  23import android.system.StructStat;
  24import android.util.DisplayMetrics;
  25import android.util.Log;
  26import android.util.LruCache;
  27import androidx.annotation.RequiresApi;
  28import androidx.annotation.StringRes;
  29import androidx.core.content.FileProvider;
  30import androidx.exifinterface.media.ExifInterface;
  31import com.google.common.base.Strings;
  32import com.google.common.collect.ImmutableList;
  33import com.google.common.io.ByteStreams;
  34import eu.siacs.conversations.Config;
  35import eu.siacs.conversations.R;
  36import eu.siacs.conversations.entities.DownloadableFile;
  37import eu.siacs.conversations.entities.Message;
  38import eu.siacs.conversations.services.AttachFileToConversationRunnable;
  39import eu.siacs.conversations.services.XmppConnectionService;
  40import eu.siacs.conversations.ui.adapter.MediaAdapter;
  41import eu.siacs.conversations.ui.util.Attachment;
  42import eu.siacs.conversations.utils.FileUtils;
  43import eu.siacs.conversations.utils.FileWriterException;
  44import eu.siacs.conversations.utils.MimeUtils;
  45import java.io.Closeable;
  46import java.io.File;
  47import java.io.FileDescriptor;
  48import java.io.FileInputStream;
  49import java.io.FileNotFoundException;
  50import java.io.FileOutputStream;
  51import java.io.IOException;
  52import java.io.InputStream;
  53import java.io.OutputStream;
  54import java.net.ServerSocket;
  55import java.net.Socket;
  56import java.text.SimpleDateFormat;
  57import java.util.ArrayList;
  58import java.util.Date;
  59import java.util.List;
  60import java.util.Locale;
  61
  62public class FileBackend {
  63
  64    private static final Object THUMBNAIL_LOCK = new Object();
  65
  66    private static final SimpleDateFormat IMAGE_DATE_FORMAT =
  67            new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
  68
  69    private static final String FILE_PROVIDER = ".files";
  70    private static final float IGNORE_PADDING = 0.15f;
  71    private final XmppConnectionService mXmppConnectionService;
  72
  73    private static final List<String> STORAGE_TYPES;
  74
  75    static {
  76        final ImmutableList.Builder<String> builder =
  77                new ImmutableList.Builder<String>()
  78                        .add(
  79                                Environment.DIRECTORY_DOWNLOADS,
  80                                Environment.DIRECTORY_PICTURES,
  81                                Environment.DIRECTORY_MOVIES,
  82                                Environment.DIRECTORY_DOCUMENTS);
  83        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
  84            builder.add(Environment.DIRECTORY_RECORDINGS);
  85        }
  86        STORAGE_TYPES = builder.build();
  87    }
  88
  89    public FileBackend(XmppConnectionService service) {
  90        this.mXmppConnectionService = service;
  91    }
  92
  93    public static long getFileSize(Context context, Uri uri) {
  94        try (final Cursor cursor =
  95                context.getContentResolver().query(uri, null, null, null, null)) {
  96            if (cursor != null && cursor.moveToFirst()) {
  97                final int index = cursor.getColumnIndex(OpenableColumns.SIZE);
  98                if (index == -1) {
  99                    return -1;
 100                }
 101                return cursor.getLong(index);
 102            }
 103            return -1;
 104        } catch (final Exception ignored) {
 105            return -1;
 106        }
 107    }
 108
 109    public static boolean allFilesUnderSize(
 110            Context context, List<Attachment> attachments, long max) {
 111        final boolean compressVideo =
 112                !AttachFileToConversationRunnable.getVideoCompression(context)
 113                        .equals("uncompressed");
 114        if (max <= 0) {
 115            Log.d(Config.LOGTAG, "server did not report max file size for http upload");
 116            return true; // exception to be compatible with HTTP Upload < v0.2
 117        }
 118        for (Attachment attachment : attachments) {
 119            if (attachment.getType() != Attachment.Type.FILE) {
 120                continue;
 121            }
 122            String mime = attachment.getMime();
 123            if (mime != null && mime.startsWith("video/") && compressVideo) {
 124                try {
 125                    Dimensions dimensions =
 126                            FileBackend.getVideoDimensions(context, attachment.getUri());
 127                    if (dimensions.getMin() > 720) {
 128                        Log.d(
 129                                Config.LOGTAG,
 130                                "do not consider video file with min width larger than 720 for size"
 131                                        + " check");
 132                        continue;
 133                    }
 134                } catch (final IOException | NotAVideoFile e) {
 135                    // ignore and fall through
 136                }
 137            }
 138            if (FileBackend.getFileSize(context, attachment.getUri()) > max) {
 139                Log.d(
 140                        Config.LOGTAG,
 141                        "not all files are under "
 142                                + max
 143                                + " bytes. suggesting falling back to jingle");
 144                return false;
 145            }
 146        }
 147        return true;
 148    }
 149
 150    public static File getBackupDirectory(final Context context) {
 151        final File conversationsDownloadDirectory =
 152                new File(
 153                        Environment.getExternalStoragePublicDirectory(
 154                                Environment.DIRECTORY_DOWNLOADS),
 155                        context.getString(R.string.app_name));
 156        return new File(conversationsDownloadDirectory, "Backup");
 157    }
 158
 159    public static File getLegacyBackupDirectory(final String app) {
 160        final File appDirectory = new File(Environment.getExternalStorageDirectory(), app);
 161        return new File(appDirectory, "Backup");
 162    }
 163
 164    private static Bitmap rotate(final Bitmap bitmap, final int degree) {
 165        if (degree == 0) {
 166            return bitmap;
 167        }
 168        final int w = bitmap.getWidth();
 169        final int h = bitmap.getHeight();
 170        final Matrix matrix = new Matrix();
 171        matrix.postRotate(degree);
 172        final Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
 173        if (!bitmap.isRecycled()) {
 174            bitmap.recycle();
 175        }
 176        return result;
 177    }
 178
 179    public static boolean isPathBlacklisted(String path) {
 180        final String androidDataPath =
 181                Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/";
 182        return path.startsWith(androidDataPath);
 183    }
 184
 185    private static Paint createAntiAliasingPaint() {
 186        Paint paint = new Paint();
 187        paint.setAntiAlias(true);
 188        paint.setFilterBitmap(true);
 189        paint.setDither(true);
 190        return paint;
 191    }
 192
 193    public static Uri getUriForUri(Context context, Uri uri) {
 194        if ("file".equals(uri.getScheme())) {
 195            return getUriForFile(context, new File(uri.getPath()));
 196        } else {
 197            return uri;
 198        }
 199    }
 200
 201    public static Uri getUriForFile(Context context, File file) {
 202        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) {
 203            try {
 204                return FileProvider.getUriForFile(context, getAuthority(context), file);
 205            } catch (IllegalArgumentException e) {
 206                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 207                    throw new SecurityException(e);
 208                } else {
 209                    return Uri.fromFile(file);
 210                }
 211            }
 212        } else {
 213            return Uri.fromFile(file);
 214        }
 215    }
 216
 217    public static String getAuthority(Context context) {
 218        return context.getPackageName() + FILE_PROVIDER;
 219    }
 220
 221    public static boolean hasAlpha(final Bitmap bitmap) {
 222        final int w = bitmap.getWidth();
 223        final int h = bitmap.getHeight();
 224        final int yStep = Math.max(1, w / 100);
 225        final int xStep = Math.max(1, h / 100);
 226        for (int x = 0; x < w; x += xStep) {
 227            for (int y = 0; y < h; y += yStep) {
 228                if (Color.alpha(bitmap.getPixel(x, y)) < 255) {
 229                    return true;
 230                }
 231            }
 232        }
 233        return false;
 234    }
 235
 236    private static int calcSampleSize(File image, int size) {
 237        BitmapFactory.Options options = new BitmapFactory.Options();
 238        options.inJustDecodeBounds = true;
 239        BitmapFactory.decodeFile(image.getAbsolutePath(), options);
 240        return calcSampleSize(options, size);
 241    }
 242
 243    private static int calcSampleSize(BitmapFactory.Options options, int size) {
 244        int height = options.outHeight;
 245        int width = options.outWidth;
 246        int inSampleSize = 1;
 247
 248        if (height > size || width > size) {
 249            int halfHeight = height / 2;
 250            int halfWidth = width / 2;
 251
 252            while ((halfHeight / inSampleSize) > size && (halfWidth / inSampleSize) > size) {
 253                inSampleSize *= 2;
 254            }
 255        }
 256        return inSampleSize;
 257    }
 258
 259    private static Dimensions getVideoDimensions(Context context, Uri uri)
 260            throws NotAVideoFile, IOException {
 261        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
 262        try {
 263            mediaMetadataRetriever.setDataSource(context, uri);
 264        } catch (RuntimeException e) {
 265            throw new NotAVideoFile(e);
 266        }
 267        return getVideoDimensions(mediaMetadataRetriever);
 268    }
 269
 270    private static Dimensions getVideoDimensionsOfFrame(
 271            MediaMetadataRetriever mediaMetadataRetriever) {
 272        Bitmap bitmap = null;
 273        try {
 274            bitmap = mediaMetadataRetriever.getFrameAtTime();
 275            return new Dimensions(bitmap.getHeight(), bitmap.getWidth());
 276        } catch (Exception e) {
 277            return null;
 278        } finally {
 279            if (bitmap != null) {
 280                bitmap.recycle();
 281            }
 282        }
 283    }
 284
 285    private static Dimensions getVideoDimensions(MediaMetadataRetriever metadataRetriever)
 286            throws NotAVideoFile, IOException {
 287        String hasVideo =
 288                metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
 289        if (hasVideo == null) {
 290            throw new NotAVideoFile();
 291        }
 292        Dimensions dimensions = getVideoDimensionsOfFrame(metadataRetriever);
 293        if (dimensions != null) {
 294            return dimensions;
 295        }
 296        final int rotation = extractRotationFromMediaRetriever(metadataRetriever);
 297        boolean rotated = rotation == 90 || rotation == 270;
 298        int height;
 299        try {
 300            String h =
 301                    metadataRetriever.extractMetadata(
 302                            MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
 303            height = Integer.parseInt(h);
 304        } catch (Exception e) {
 305            height = -1;
 306        }
 307        int width;
 308        try {
 309            String w =
 310                    metadataRetriever.extractMetadata(
 311                            MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
 312            width = Integer.parseInt(w);
 313        } catch (Exception e) {
 314            width = -1;
 315        }
 316        metadataRetriever.release();
 317        Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height);
 318        return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
 319    }
 320
 321    private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
 322        String r =
 323                metadataRetriever.extractMetadata(
 324                        MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
 325        try {
 326            return Integer.parseInt(r);
 327        } catch (Exception e) {
 328            return 0;
 329        }
 330    }
 331
 332    public static void close(final Closeable stream) {
 333        if (stream != null) {
 334            try {
 335                stream.close();
 336            } catch (Exception e) {
 337                Log.d(Config.LOGTAG, "unable to close stream", e);
 338            }
 339        }
 340    }
 341
 342    public static void close(final Socket socket) {
 343        if (socket != null) {
 344            try {
 345                socket.close();
 346            } catch (IOException e) {
 347                Log.d(Config.LOGTAG, "unable to close socket", e);
 348            }
 349        }
 350    }
 351
 352    public static void close(final ServerSocket socket) {
 353        if (socket != null) {
 354            try {
 355                socket.close();
 356            } catch (IOException e) {
 357                Log.d(Config.LOGTAG, "unable to close server socket", e);
 358            }
 359        }
 360    }
 361
 362    public static boolean dangerousFile(final Uri uri) {
 363        if (uri == null || Strings.isNullOrEmpty(uri.getScheme())) {
 364            return true;
 365        }
 366        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
 367            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 368                // On Android 7 (and apps that target 7) it is now longer possible to share files
 369                // with a file scheme. By now you should probably not be running apps that target
 370                // anything less than 7 any more
 371                return true;
 372            } else {
 373                return isFileOwnedByProcess(uri);
 374            }
 375        }
 376        return false;
 377    }
 378
 379    private static boolean isFileOwnedByProcess(final Uri uri) {
 380        final String path = uri.getPath();
 381        if (path == null) {
 382            return true;
 383        }
 384        try (final var pfd =
 385                ParcelFileDescriptor.open(new File(path), ParcelFileDescriptor.MODE_READ_ONLY)) {
 386            final FileDescriptor fd = pfd.getFileDescriptor();
 387            final StructStat st = Os.fstat(fd);
 388            return st.st_uid == android.os.Process.myUid();
 389        } catch (final Exception e) {
 390            // when in doubt. better safe than sorry
 391            return true;
 392        }
 393    }
 394
 395    public static Uri getMediaUri(Context context, File file) {
 396        final String filePath = file.getAbsolutePath();
 397        try (final Cursor cursor =
 398                context.getContentResolver()
 399                        .query(
 400                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
 401                                new String[] {MediaStore.Images.Media._ID},
 402                                MediaStore.Images.Media.DATA + "=? ",
 403                                new String[] {filePath},
 404                                null)) {
 405            if (cursor != null && cursor.moveToFirst()) {
 406                final int id =
 407                        cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
 408                return Uri.withAppendedPath(
 409                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
 410            } else {
 411                return null;
 412            }
 413        } catch (final Exception e) {
 414            return null;
 415        }
 416    }
 417
 418    public static void updateFileParams(Message message, String url, long size) {
 419        message.setBody(url + '|' + size);
 420    }
 421
 422    public Bitmap getPreviewForUri(Attachment attachment, int size, boolean cacheOnly) {
 423        final String key = "attachment_" + attachment.getUuid().toString() + "_" + size;
 424        final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
 425        Bitmap bitmap = cache.get(key);
 426        if (bitmap != null || cacheOnly) {
 427            return bitmap;
 428        }
 429        final String mime = attachment.getMime();
 430        if ("application/pdf".equals(mime)) {
 431            bitmap = cropCenterSquarePdf(attachment.getUri(), size);
 432            drawOverlay(
 433                    bitmap,
 434                    paintOverlayBlackPdf(bitmap)
 435                            ? R.drawable.open_pdf_black
 436                            : R.drawable.open_pdf_white,
 437                    0.75f);
 438        } else if (mime != null && mime.startsWith("video/")) {
 439            bitmap = cropCenterSquareVideo(attachment.getUri(), size);
 440            drawOverlay(
 441                    bitmap,
 442                    paintOverlayBlack(bitmap)
 443                            ? R.drawable.play_video_black
 444                            : R.drawable.play_video_white,
 445                    0.75f);
 446        } else {
 447            bitmap = cropCenterSquare(attachment.getUri(), size);
 448            if (bitmap != null && "image/gif".equals(mime)) {
 449                Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
 450                drawOverlay(
 451                        withGifOverlay,
 452                        paintOverlayBlack(withGifOverlay)
 453                                ? R.drawable.play_gif_black
 454                                : R.drawable.play_gif_white,
 455                        1.0f);
 456                bitmap.recycle();
 457                bitmap = withGifOverlay;
 458            }
 459        }
 460        if (bitmap != null) {
 461            cache.put(key, bitmap);
 462        }
 463        return bitmap;
 464    }
 465
 466    public void updateMediaScanner(File file) {
 467        updateMediaScanner(file, null);
 468    }
 469
 470    public void updateMediaScanner(File file, final Runnable callback) {
 471        MediaScannerConnection.scanFile(
 472                mXmppConnectionService,
 473                new String[] {file.getAbsolutePath()},
 474                null,
 475                new MediaScannerConnection.MediaScannerConnectionClient() {
 476                    @Override
 477                    public void onMediaScannerConnected() {}
 478
 479                    @Override
 480                    public void onScanCompleted(String path, Uri uri) {
 481                        if (callback != null && file.getAbsolutePath().equals(path)) {
 482                            callback.run();
 483                        } else {
 484                            Log.d(Config.LOGTAG, "media scanner scanned wrong file");
 485                            if (callback != null) {
 486                                callback.run();
 487                            }
 488                        }
 489                    }
 490                });
 491    }
 492
 493    public boolean deleteFile(Message message) {
 494        File file = getFile(message);
 495        if (file.delete()) {
 496            updateMediaScanner(file);
 497            return true;
 498        } else {
 499            return false;
 500        }
 501    }
 502
 503    public DownloadableFile getFile(Message message) {
 504        return getFile(message, true);
 505    }
 506
 507    public DownloadableFile getFileForPath(String path) {
 508        return getFileForPath(
 509                path,
 510                MimeUtils.guessMimeTypeFromExtension(MimeUtils.extractRelevantExtension(path)));
 511    }
 512
 513    private DownloadableFile getFileForPath(final String path, final String mime) {
 514        if (path.startsWith("/")) {
 515            return new DownloadableFile(path);
 516        } else {
 517            return getLegacyFileForFilename(path, mime);
 518        }
 519    }
 520
 521    public DownloadableFile getLegacyFileForFilename(final String filename, final String mime) {
 522        if (Strings.isNullOrEmpty(mime)) {
 523            return new DownloadableFile(getLegacyStorageLocation("Files"), filename);
 524        } else if (mime.startsWith("image/")) {
 525            return new DownloadableFile(getLegacyStorageLocation("Images"), filename);
 526        } else if (mime.startsWith("video/")) {
 527            return new DownloadableFile(getLegacyStorageLocation("Videos"), filename);
 528        } else {
 529            return new DownloadableFile(getLegacyStorageLocation("Files"), filename);
 530        }
 531    }
 532
 533    public boolean isInternalFile(final File file) {
 534        final File internalFile = getFileForPath(file.getName());
 535        return file.getAbsolutePath().equals(internalFile.getAbsolutePath());
 536    }
 537
 538    public DownloadableFile getFile(Message message, boolean decrypted) {
 539        final boolean encrypted =
 540                !decrypted
 541                        && (message.getEncryption() == Message.ENCRYPTION_PGP
 542                                || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
 543        String path = message.getRelativeFilePath();
 544        if (path == null) {
 545            path = message.getUuid();
 546        }
 547        final DownloadableFile file = getFileForPath(path, message.getMimeType());
 548        if (encrypted) {
 549            return new DownloadableFile(
 550                    mXmppConnectionService.getCacheDir(),
 551                    String.format("%s.%s", file.getName(), "pgp"));
 552        } else {
 553            return file;
 554        }
 555    }
 556
 557    public List<Attachment> convertToAttachments(List<DatabaseBackend.FilePath> relativeFilePaths) {
 558        final List<Attachment> attachments = new ArrayList<>();
 559        for (final DatabaseBackend.FilePath relativeFilePath : relativeFilePaths) {
 560            final String mime =
 561                    MimeUtils.guessMimeTypeFromExtension(
 562                            MimeUtils.extractRelevantExtension(relativeFilePath.path));
 563            final File file = getFileForPath(relativeFilePath.path, mime);
 564            attachments.add(Attachment.of(relativeFilePath.uuid, file, mime));
 565        }
 566        return attachments;
 567    }
 568
 569    private File getLegacyStorageLocation(final String type) {
 570        if (Config.ONLY_INTERNAL_STORAGE) {
 571            return new File(mXmppConnectionService.getFilesDir(), type);
 572        } else {
 573            final File appDirectory =
 574                    new File(
 575                            Environment.getExternalStorageDirectory(),
 576                            mXmppConnectionService.getString(R.string.app_name));
 577            final File appMediaDirectory = new File(appDirectory, "Media");
 578            final String locationName =
 579                    String.format(
 580                            "%s %s", mXmppConnectionService.getString(R.string.app_name), type);
 581            return new File(appMediaDirectory, locationName);
 582        }
 583    }
 584
 585    private Bitmap resize(final Bitmap originalBitmap, int size) throws IOException {
 586        int w = originalBitmap.getWidth();
 587        int h = originalBitmap.getHeight();
 588        if (w <= 0 || h <= 0) {
 589            throw new IOException("Decoded bitmap reported bounds smaller 0");
 590        } else if (Math.max(w, h) > size) {
 591            int scalledW;
 592            int scalledH;
 593            if (w <= h) {
 594                scalledW = Math.max((int) (w / ((double) h / size)), 1);
 595                scalledH = size;
 596            } else {
 597                scalledW = size;
 598                scalledH = Math.max((int) (h / ((double) w / size)), 1);
 599            }
 600            final Bitmap result =
 601                    Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
 602            if (!originalBitmap.isRecycled()) {
 603                originalBitmap.recycle();
 604            }
 605            return result;
 606        } else {
 607            return originalBitmap;
 608        }
 609    }
 610
 611    public boolean useImageAsIs(final Uri uri) {
 612        final String path = getOriginalPath(uri);
 613        if (path == null || isPathBlacklisted(path)) {
 614            return false;
 615        }
 616        final File file = new File(path);
 617        long size = file.length();
 618        if (size == 0
 619                || size
 620                        >= mXmppConnectionService
 621                                .getResources()
 622                                .getInteger(R.integer.auto_accept_filesize)) {
 623            return false;
 624        }
 625        BitmapFactory.Options options = new BitmapFactory.Options();
 626        options.inJustDecodeBounds = true;
 627        try {
 628            final InputStream inputStream =
 629                    mXmppConnectionService.getContentResolver().openInputStream(uri);
 630            BitmapFactory.decodeStream(inputStream, null, options);
 631            close(inputStream);
 632            if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
 633                return false;
 634            }
 635            return (options.outWidth <= Config.IMAGE_SIZE
 636                    && options.outHeight <= Config.IMAGE_SIZE
 637                    && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
 638        } catch (FileNotFoundException e) {
 639            Log.d(Config.LOGTAG, "unable to get image dimensions", e);
 640            return false;
 641        }
 642    }
 643
 644    public String getOriginalPath(final Uri uri) {
 645        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
 646            // On Android 11+ we don’t have access to the original file
 647            return null;
 648        } else {
 649            return FileUtils.getPath(mXmppConnectionService, uri);
 650        }
 651    }
 652
 653    private void copyFileToPrivateStorage(final File file, final Uri uri) throws FileCopyException {
 654        final var parentDirectory = file.getParentFile();
 655        if (parentDirectory != null && parentDirectory.mkdirs()) {
 656            Log.d(Config.LOGTAG, "created directory " + parentDirectory.getAbsolutePath());
 657        }
 658        try {
 659            if (file.createNewFile()) {
 660                Log.d(Config.LOGTAG, "created empty file " + file.getAbsolutePath());
 661            }
 662        } catch (final IOException e) {
 663            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 664        }
 665        try (final OutputStream os = new FileOutputStream(file);
 666                final InputStream is =
 667                        mXmppConnectionService.getContentResolver().openInputStream(uri)) {
 668            if (is == null) {
 669                throw new FileCopyException(R.string.error_file_not_found);
 670            }
 671            try {
 672                ByteStreams.copy(is, os);
 673            } catch (final IOException e) {
 674                throw new FileWriterException(file);
 675            }
 676            try {
 677                os.flush();
 678            } catch (final IOException e) {
 679                throw new FileWriterException(file);
 680            }
 681        } catch (final FileNotFoundException e) {
 682            cleanup(file);
 683            throw new FileCopyException(R.string.error_file_not_found);
 684        } catch (final FileWriterException e) {
 685            cleanup(file);
 686            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 687        } catch (final SecurityException | IllegalStateException | IllegalArgumentException e) {
 688            cleanup(file);
 689            throw new FileCopyException(R.string.error_security_exception);
 690        } catch (final IOException e) {
 691            cleanup(file);
 692            throw new FileCopyException(R.string.error_io_exception);
 693        }
 694    }
 695
 696    public void copyFileToPrivateStorage(final Message message, final Uri uri, final String type)
 697            throws FileCopyException {
 698        final String mime =
 699                MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
 700        Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
 701        String extension = MimeUtils.guessExtensionFromMimeType(mime);
 702        if (extension == null) {
 703            Log.d(Config.LOGTAG, "extension from mime type was null");
 704            extension = getExtensionFromUri(uri);
 705        }
 706        if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
 707            extension = "oga";
 708        }
 709        setupRelativeFilePath(message, String.format("%s.%s", message.getUuid(), extension));
 710        copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
 711    }
 712
 713    private String getExtensionFromUri(final Uri uri) {
 714        final String[] projection = {MediaStore.MediaColumns.DATA};
 715        String filename = null;
 716        try (final Cursor cursor =
 717                mXmppConnectionService
 718                        .getContentResolver()
 719                        .query(uri, projection, null, null, null)) {
 720            if (cursor != null && cursor.moveToFirst()) {
 721                filename = cursor.getString(0);
 722            }
 723        } catch (final Exception e) {
 724            filename = null;
 725        }
 726        if (filename == null) {
 727            final List<String> segments = uri.getPathSegments();
 728            if (segments.size() > 0) {
 729                filename = segments.get(segments.size() - 1);
 730            }
 731        }
 732        final int pos = filename == null ? -1 : filename.lastIndexOf('.');
 733        return pos > 0 ? filename.substring(pos + 1) : null;
 734    }
 735
 736    private void copyImageToPrivateStorage(File file, Uri image, int sampleSize)
 737            throws FileCopyException, ImageCompressionException {
 738        final File parent = file.getParentFile();
 739        if (parent != null && parent.mkdirs()) {
 740            Log.d(Config.LOGTAG, "created parent directory");
 741        }
 742        InputStream is = null;
 743        OutputStream os = null;
 744        try {
 745            if (!file.exists() && !file.createNewFile()) {
 746                throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 747            }
 748            is = mXmppConnectionService.getContentResolver().openInputStream(image);
 749            if (is == null) {
 750                throw new FileCopyException(R.string.error_not_an_image_file);
 751            }
 752            final Bitmap originalBitmap;
 753            final BitmapFactory.Options options = new BitmapFactory.Options();
 754            final int inSampleSize = (int) Math.pow(2, sampleSize);
 755            Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
 756            options.inSampleSize = inSampleSize;
 757            originalBitmap = BitmapFactory.decodeStream(is, null, options);
 758            is.close();
 759            if (originalBitmap == null) {
 760                throw new ImageCompressionException("Source file was not an image");
 761            }
 762            if (!"image/jpeg".equals(options.outMimeType) && hasAlpha(originalBitmap)) {
 763                originalBitmap.recycle();
 764                throw new ImageCompressionException("Source file had alpha channel");
 765            }
 766            Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
 767            final int rotation = getRotation(mXmppConnectionService, image);
 768            scaledBitmap = rotate(scaledBitmap, rotation);
 769            boolean targetSizeReached = false;
 770            int quality = Config.IMAGE_QUALITY;
 771            final int imageMaxSize =
 772                    mXmppConnectionService
 773                            .getResources()
 774                            .getInteger(R.integer.auto_accept_filesize);
 775            while (!targetSizeReached) {
 776                os = new FileOutputStream(file);
 777                Log.d(Config.LOGTAG, "compressing image with quality " + quality);
 778                boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
 779                if (!success) {
 780                    throw new FileCopyException(R.string.error_compressing_image);
 781                }
 782                os.flush();
 783                final long fileSize = file.length();
 784                Log.d(Config.LOGTAG, "achieved file size of " + fileSize);
 785                targetSizeReached = fileSize <= imageMaxSize || quality <= 50;
 786                quality -= 5;
 787            }
 788            scaledBitmap.recycle();
 789        } catch (final FileNotFoundException e) {
 790            cleanup(file);
 791            throw new FileCopyException(R.string.error_file_not_found);
 792        } catch (final IOException e) {
 793            cleanup(file);
 794            throw new FileCopyException(R.string.error_io_exception);
 795        } catch (SecurityException e) {
 796            cleanup(file);
 797            throw new FileCopyException(R.string.error_security_exception_during_image_copy);
 798        } catch (final OutOfMemoryError e) {
 799            ++sampleSize;
 800            if (sampleSize <= 3) {
 801                copyImageToPrivateStorage(file, image, sampleSize);
 802            } else {
 803                throw new FileCopyException(R.string.error_out_of_memory);
 804            }
 805        } finally {
 806            close(os);
 807            close(is);
 808        }
 809    }
 810
 811    private static void cleanup(final File file) {
 812        try {
 813            file.delete();
 814        } catch (Exception e) {
 815
 816        }
 817    }
 818
 819    public void copyImageToPrivateStorage(File file, Uri image)
 820            throws FileCopyException, ImageCompressionException {
 821        Log.d(
 822                Config.LOGTAG,
 823                "copy image ("
 824                        + image.toString()
 825                        + ") to private storage "
 826                        + file.getAbsolutePath());
 827        copyImageToPrivateStorage(file, image, 0);
 828    }
 829
 830    public void copyImageToPrivateStorage(Message message, Uri image)
 831            throws FileCopyException, ImageCompressionException {
 832        final String filename;
 833        switch (Config.IMAGE_FORMAT) {
 834            case JPEG:
 835                filename = String.format("%s.%s", message.getUuid(), "jpg");
 836                break;
 837            case PNG:
 838                filename = String.format("%s.%s", message.getUuid(), "png");
 839                break;
 840            case WEBP:
 841                filename = String.format("%s.%s", message.getUuid(), "webp");
 842                break;
 843            default:
 844                throw new IllegalStateException("Unknown image format");
 845        }
 846        setupRelativeFilePath(message, filename);
 847        copyImageToPrivateStorage(getFile(message), image);
 848        updateFileParams(message);
 849    }
 850
 851    public void setupRelativeFilePath(final Message message, final String filename) {
 852        final String extension = MimeUtils.extractRelevantExtension(filename);
 853        final String mime = MimeUtils.guessMimeTypeFromExtension(extension);
 854        setupRelativeFilePath(message, filename, mime);
 855    }
 856
 857    public File getStorageLocation(final String filename, final String mime) {
 858        final File parentDirectory;
 859        if (Strings.isNullOrEmpty(mime)) {
 860            parentDirectory =
 861                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
 862        } else if (mime.startsWith("image/")) {
 863            parentDirectory =
 864                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
 865        } else if (mime.startsWith("video/")) {
 866            parentDirectory =
 867                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
 868        } else if (MediaAdapter.DOCUMENT_MIMES.contains(mime)) {
 869            parentDirectory =
 870                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
 871        } else {
 872            parentDirectory =
 873                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
 874        }
 875        final File appDirectory =
 876                new File(parentDirectory, mXmppConnectionService.getString(R.string.app_name));
 877        return new File(appDirectory, filename);
 878    }
 879
 880    public static boolean inConversationsDirectory(final Context context, String path) {
 881        final File fileDirectory = new File(path).getParentFile();
 882        for (final String type : STORAGE_TYPES) {
 883            final File typeDirectory =
 884                    new File(
 885                            Environment.getExternalStoragePublicDirectory(type),
 886                            context.getString(R.string.app_name));
 887            if (typeDirectory.equals(fileDirectory)) {
 888                return true;
 889            }
 890        }
 891        return false;
 892    }
 893
 894    public void setupRelativeFilePath(
 895            final Message message, final String filename, final String mime) {
 896        final File file = getStorageLocation(filename, mime);
 897        message.setRelativeFilePath(file.getAbsolutePath());
 898    }
 899
 900    public boolean unusualBounds(final Uri image) {
 901        try {
 902            final BitmapFactory.Options options = new BitmapFactory.Options();
 903            options.inJustDecodeBounds = true;
 904            final InputStream inputStream =
 905                    mXmppConnectionService.getContentResolver().openInputStream(image);
 906            BitmapFactory.decodeStream(inputStream, null, options);
 907            close(inputStream);
 908            float ratio = (float) options.outHeight / options.outWidth;
 909            return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
 910        } catch (final Exception e) {
 911            Log.w(Config.LOGTAG, "unable to detect image bounds", e);
 912            return false;
 913        }
 914    }
 915
 916    private int getRotation(final File file) {
 917        try (final InputStream inputStream = new FileInputStream(file)) {
 918            return getRotation(inputStream);
 919        } catch (Exception e) {
 920            return 0;
 921        }
 922    }
 923
 924    private static int getRotation(final Context context, final Uri image) {
 925        try (final InputStream is = context.getContentResolver().openInputStream(image)) {
 926            return is == null ? 0 : getRotation(is);
 927        } catch (final Exception e) {
 928            return 0;
 929        }
 930    }
 931
 932    private static int getRotation(final InputStream inputStream) throws IOException {
 933        final ExifInterface exif = new ExifInterface(inputStream);
 934        final int orientation =
 935                exif.getAttributeInt(
 936                        ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
 937        switch (orientation) {
 938            case ExifInterface.ORIENTATION_ROTATE_180:
 939                return 180;
 940            case ExifInterface.ORIENTATION_ROTATE_90:
 941                return 90;
 942            case ExifInterface.ORIENTATION_ROTATE_270:
 943                return 270;
 944            default:
 945                return 0;
 946        }
 947    }
 948
 949    public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
 950        final String uuid = message.getUuid();
 951        final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
 952        Bitmap thumbnail = cache.get(uuid);
 953        if ((thumbnail == null) && (!cacheOnly)) {
 954            synchronized (THUMBNAIL_LOCK) {
 955                thumbnail = cache.get(uuid);
 956                if (thumbnail != null) {
 957                    return thumbnail;
 958                }
 959                DownloadableFile file = getFile(message);
 960                final String mime = file.getMimeType();
 961                if ("application/pdf".equals(mime)) {
 962                    thumbnail = getPdfDocumentPreview(file, size);
 963                } else if (mime.startsWith("video/")) {
 964                    thumbnail = getVideoPreview(file, size);
 965                } else {
 966                    final Bitmap fullSize = getFullSizeImagePreview(file, size);
 967                    if (fullSize == null) {
 968                        throw new FileNotFoundException();
 969                    }
 970                    thumbnail = resize(fullSize, size);
 971                    thumbnail = rotate(thumbnail, getRotation(file));
 972                    if (mime.equals("image/gif")) {
 973                        Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
 974                        drawOverlay(
 975                                withGifOverlay,
 976                                paintOverlayBlack(withGifOverlay)
 977                                        ? R.drawable.play_gif_black
 978                                        : R.drawable.play_gif_white,
 979                                1.0f);
 980                        thumbnail.recycle();
 981                        thumbnail = withGifOverlay;
 982                    }
 983                }
 984                cache.put(uuid, thumbnail);
 985            }
 986        }
 987        return thumbnail;
 988    }
 989
 990    private Bitmap getFullSizeImagePreview(File file, int size) {
 991        BitmapFactory.Options options = new BitmapFactory.Options();
 992        options.inSampleSize = calcSampleSize(file, size);
 993        try {
 994            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 995        } catch (OutOfMemoryError e) {
 996            options.inSampleSize *= 2;
 997            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 998        }
 999    }
1000
1001    private void drawOverlay(Bitmap bitmap, int resource, float factor) {
1002        Bitmap overlay =
1003                BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
1004        Canvas canvas = new Canvas(bitmap);
1005        float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
1006        Log.d(
1007                Config.LOGTAG,
1008                "target size overlay: "
1009                        + targetSize
1010                        + " overlay bitmap size was "
1011                        + overlay.getHeight());
1012        float left = (canvas.getWidth() - targetSize) / 2.0f;
1013        float top = (canvas.getHeight() - targetSize) / 2.0f;
1014        RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
1015        canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
1016    }
1017
1018    /** https://stackoverflow.com/a/3943023/210897 */
1019    private boolean paintOverlayBlack(final Bitmap bitmap) {
1020        final int h = bitmap.getHeight();
1021        final int w = bitmap.getWidth();
1022        int record = 0;
1023        for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
1024            for (int x = Math.round(w * IGNORE_PADDING);
1025                    x < w - Math.round(w * IGNORE_PADDING);
1026                    ++x) {
1027                int pixel = bitmap.getPixel(x, y);
1028                if ((Color.red(pixel) * 0.299
1029                                + Color.green(pixel) * 0.587
1030                                + Color.blue(pixel) * 0.114)
1031                        > 186) {
1032                    --record;
1033                } else {
1034                    ++record;
1035                }
1036            }
1037        }
1038        return record < 0;
1039    }
1040
1041    private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
1042        final int h = bitmap.getHeight();
1043        final int w = bitmap.getWidth();
1044        int white = 0;
1045        for (int y = 0; y < h; ++y) {
1046            for (int x = 0; x < w; ++x) {
1047                int pixel = bitmap.getPixel(x, y);
1048                if ((Color.red(pixel) * 0.299
1049                                + Color.green(pixel) * 0.587
1050                                + Color.blue(pixel) * 0.114)
1051                        > 186) {
1052                    white++;
1053                }
1054            }
1055        }
1056        return white > (h * w * 0.4f);
1057    }
1058
1059    private Bitmap cropCenterSquareVideo(Uri uri, int size) {
1060        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1061        Bitmap frame;
1062        try {
1063            metadataRetriever.setDataSource(mXmppConnectionService, uri);
1064            frame = metadataRetriever.getFrameAtTime(0);
1065            metadataRetriever.release();
1066            return cropCenterSquare(frame, size);
1067        } catch (Exception e) {
1068            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1069            frame.eraseColor(0xff000000);
1070            return frame;
1071        }
1072    }
1073
1074    private Bitmap getVideoPreview(final File file, final int size) {
1075        final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1076        Bitmap frame;
1077        try {
1078            metadataRetriever.setDataSource(file.getAbsolutePath());
1079            frame = metadataRetriever.getFrameAtTime(0);
1080            metadataRetriever.release();
1081            frame = resize(frame, size);
1082        } catch (IOException | RuntimeException e) {
1083            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1084            frame.eraseColor(0xff000000);
1085        }
1086        drawOverlay(
1087                frame,
1088                paintOverlayBlack(frame)
1089                        ? R.drawable.play_video_black
1090                        : R.drawable.play_video_white,
1091                0.75f);
1092        return frame;
1093    }
1094
1095    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1096    private Bitmap getPdfDocumentPreview(final File file, final int size) {
1097        try {
1098            final ParcelFileDescriptor fileDescriptor =
1099                    ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1100            final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
1101            drawOverlay(
1102                    rendered,
1103                    paintOverlayBlackPdf(rendered)
1104                            ? R.drawable.open_pdf_black
1105                            : R.drawable.open_pdf_white,
1106                    0.75f);
1107            return rendered;
1108        } catch (final IOException | SecurityException e) {
1109            Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
1110            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1111            placeholder.eraseColor(0xff000000);
1112            return placeholder;
1113        }
1114    }
1115
1116    private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
1117        try {
1118            ParcelFileDescriptor fileDescriptor =
1119                    mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
1120            final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1121            return cropCenterSquare(bitmap, size);
1122        } catch (Exception e) {
1123            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1124            placeholder.eraseColor(0xff000000);
1125            return placeholder;
1126        }
1127    }
1128
1129    private Bitmap renderPdfDocument(
1130            ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1131        final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1132        final PdfRenderer.Page page = pdfRenderer.openPage(0);
1133        final Dimensions dimensions =
1134                scalePdfDimensions(
1135                        new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1136        final Bitmap rendered =
1137                Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1138        rendered.eraseColor(0xffffffff);
1139        page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1140        page.close();
1141        pdfRenderer.close();
1142        fileDescriptor.close();
1143        return rendered;
1144    }
1145
1146    public Uri getTakePhotoUri() {
1147        final String filename =
1148                String.format("IMG_%s.%s", IMAGE_DATE_FORMAT.format(new Date()), "jpg");
1149        final File directory;
1150        if (Config.ONLY_INTERNAL_STORAGE) {
1151            directory = new File(mXmppConnectionService.getCacheDir(), "Camera");
1152        } else {
1153            directory =
1154                    new File(
1155                            Environment.getExternalStoragePublicDirectory(
1156                                    Environment.DIRECTORY_DCIM),
1157                            "Camera");
1158        }
1159        final File file = new File(directory, filename);
1160        file.getParentFile().mkdirs();
1161        return getUriForFile(mXmppConnectionService, file);
1162    }
1163
1164    public void deleteHistoricAvatarPath() {
1165        delete(getHistoricAvatarPath());
1166    }
1167
1168    private void delete(final File file) {
1169        if (file.isDirectory()) {
1170            final File[] files = file.listFiles();
1171            if (files != null) {
1172                for (final File f : files) {
1173                    delete(f);
1174                }
1175            }
1176        }
1177        if (file.delete()) {
1178            Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1179        }
1180    }
1181
1182    private File getHistoricAvatarPath() {
1183        return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1184    }
1185
1186    public File getAvatarFile(final String avatar) {
1187        return getAvatarFile(mXmppConnectionService, avatar);
1188    }
1189
1190    public static File getAvatarFile(Context context, final String avatar) {
1191        return new File(context.getCacheDir(), "/avatars/" + avatar);
1192    }
1193
1194    public Uri getAvatarUri(String avatar) {
1195        return Uri.fromFile(getAvatarFile(avatar));
1196    }
1197
1198    public Bitmap cropCenterSquare(final Uri image, final int size) {
1199        return cropCenterSquare(mXmppConnectionService, image, size);
1200    }
1201
1202    public static Bitmap cropCenterSquare(final Context context, final Uri image, final int size) {
1203        if (image == null) {
1204            return null;
1205        }
1206        final BitmapFactory.Options options = new BitmapFactory.Options();
1207        try {
1208            options.inSampleSize = calcSampleSize(context, image, size);
1209        } catch (final IOException | SecurityException e) {
1210            Log.d(Config.LOGTAG, "unable to calculate sample size for " + image, e);
1211            return null;
1212        }
1213        try (final InputStream is = context.getContentResolver().openInputStream(image)) {
1214            if (is == null) {
1215                return null;
1216            }
1217            final var originalBitmap = BitmapFactory.decodeStream(is, null, options);
1218            if (originalBitmap == null) {
1219                return null;
1220            } else {
1221                final var bitmap = rotate(originalBitmap, getRotation(context, image));
1222                return cropCenterSquare(bitmap, size);
1223            }
1224        } catch (final SecurityException | IOException e) {
1225            Log.d(Config.LOGTAG, "unable to open file " + image, e);
1226            return null;
1227        }
1228    }
1229
1230    public Bitmap cropCenter(final Uri image, final int newHeight, final int newWidth) {
1231        if (image == null) {
1232            return null;
1233        }
1234        InputStream is = null;
1235        try {
1236            BitmapFactory.Options options = new BitmapFactory.Options();
1237            options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1238            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1239            if (is == null) {
1240                return null;
1241            }
1242            Bitmap source = BitmapFactory.decodeStream(is, null, options);
1243            if (source == null) {
1244                return null;
1245            }
1246            int sourceWidth = source.getWidth();
1247            int sourceHeight = source.getHeight();
1248            float xScale = (float) newWidth / sourceWidth;
1249            float yScale = (float) newHeight / sourceHeight;
1250            float scale = Math.max(xScale, yScale);
1251            float scaledWidth = scale * sourceWidth;
1252            float scaledHeight = scale * sourceHeight;
1253            float left = (newWidth - scaledWidth) / 2;
1254            float top = (newHeight - scaledHeight) / 2;
1255
1256            RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1257            Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1258            Canvas canvas = new Canvas(dest);
1259            canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1260            if (source.isRecycled()) {
1261                source.recycle();
1262            }
1263            return dest;
1264        } catch (SecurityException e) {
1265            return null; // android 6.0 with revoked permissions for example
1266        } catch (IOException e) {
1267            return null;
1268        } finally {
1269            close(is);
1270        }
1271    }
1272
1273    public static Bitmap cropCenterSquare(final Bitmap input, final int sizeIn) {
1274        final int w = input.getWidth();
1275        final int h = input.getHeight();
1276        final int size;
1277        final float outWidth;
1278        final float outHeight;
1279        if (w < sizeIn || h < sizeIn) {
1280            size = Math.min(w, h);
1281            outWidth = w;
1282            outHeight = h;
1283        } else {
1284            size = sizeIn;
1285            final float scale = Math.max((float) sizeIn / h, (float) sizeIn / w);
1286            outWidth = scale * w;
1287            outHeight = scale * h;
1288        }
1289        float left = (size - outWidth) / 2;
1290        float top = (size - outHeight) / 2;
1291        final var target = new RectF(left, top, left + outWidth, top + outHeight);
1292
1293        final var output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1294        final var canvas = new Canvas(output);
1295        canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1296        if (!input.isRecycled()) {
1297            input.recycle();
1298        }
1299        return output;
1300    }
1301
1302    private int calcSampleSize(final Uri image, int size) throws IOException, SecurityException {
1303        return calcSampleSize(mXmppConnectionService, image, size);
1304    }
1305
1306    private static int calcSampleSize(final Context context, final Uri image, int size)
1307            throws IOException, SecurityException {
1308        final BitmapFactory.Options options = new BitmapFactory.Options();
1309        options.inJustDecodeBounds = true;
1310        try (final InputStream inputStream = context.getContentResolver().openInputStream(image)) {
1311            BitmapFactory.decodeStream(inputStream, null, options);
1312            return calcSampleSize(options, size);
1313        }
1314    }
1315
1316    public void updateFileParams(final Message message) {
1317        updateFileParams(message, null);
1318    }
1319
1320    public void updateFileParams(final Message message, final String url) {
1321        final boolean encrypted =
1322                message.getEncryption() == Message.ENCRYPTION_PGP
1323                        || message.getEncryption() == Message.ENCRYPTION_DECRYPTED;
1324        final DownloadableFile file = getFile(message);
1325        final String mime = file.getMimeType();
1326        final boolean image =
1327                message.getType() == Message.TYPE_IMAGE
1328                        || (mime != null && mime.startsWith("image/"));
1329        final boolean privateMessage = message.isPrivateMessage();
1330        final StringBuilder body = new StringBuilder();
1331        if (url != null) {
1332            body.append(url);
1333        }
1334        if (encrypted && !file.exists()) {
1335            Log.d(Config.LOGTAG, "skipping updateFileParams because file is encrypted");
1336            final DownloadableFile encryptedFile = getFile(message, false);
1337            body.append('|').append(encryptedFile.getSize());
1338        } else {
1339            Log.d(Config.LOGTAG, "running updateFileParams");
1340            final boolean ambiguous = MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime);
1341            final boolean video = mime != null && mime.startsWith("video/");
1342            final boolean audio = mime != null && mime.startsWith("audio/");
1343            final boolean pdf = "application/pdf".equals(mime);
1344            body.append('|').append(file.getSize());
1345            if (ambiguous) {
1346                try {
1347                    final Dimensions dimensions = getVideoDimensions(file);
1348                    if (dimensions.valid()) {
1349                        Log.d(Config.LOGTAG, "ambiguous file " + mime + " is video");
1350                        body.append('|')
1351                                .append(dimensions.width)
1352                                .append('|')
1353                                .append(dimensions.height);
1354                    } else {
1355                        Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1356                        body.append("|0|0|").append(getMediaRuntime(file));
1357                    }
1358                } catch (final IOException | NotAVideoFile e) {
1359                    Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1360                    body.append("|0|0|").append(getMediaRuntime(file));
1361                }
1362            } else if (image || video || pdf) {
1363                try {
1364                    final Dimensions dimensions;
1365                    if (video) {
1366                        dimensions = getVideoDimensions(file);
1367                    } else if (pdf) {
1368                        dimensions = getPdfDocumentDimensions(file);
1369                    } else {
1370                        dimensions = getImageDimensions(file);
1371                    }
1372                    if (dimensions.valid()) {
1373                        body.append('|')
1374                                .append(dimensions.width)
1375                                .append('|')
1376                                .append(dimensions.height);
1377                    }
1378                } catch (final IOException | NotAVideoFile notAVideoFile) {
1379                    Log.d(
1380                            Config.LOGTAG,
1381                            "file with mime type " + file.getMimeType() + " was not a video file");
1382                    // fall threw
1383                }
1384            } else if (audio) {
1385                body.append("|0|0|").append(getMediaRuntime(file));
1386            }
1387        }
1388        message.setBody(body.toString());
1389        message.setDeleted(false);
1390        message.setType(
1391                privateMessage
1392                        ? Message.TYPE_PRIVATE_FILE
1393                        : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
1394    }
1395
1396    private int getMediaRuntime(final File file) {
1397        try {
1398            final MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1399            mediaMetadataRetriever.setDataSource(file.toString());
1400            final String value =
1401                    mediaMetadataRetriever.extractMetadata(
1402                            MediaMetadataRetriever.METADATA_KEY_DURATION);
1403            if (Strings.isNullOrEmpty(value)) {
1404                return 0;
1405            }
1406            return Integer.parseInt(value);
1407        } catch (final Exception e) {
1408            return 0;
1409        }
1410    }
1411
1412    private Dimensions getImageDimensions(File file) {
1413        final BitmapFactory.Options options = new BitmapFactory.Options();
1414        options.inJustDecodeBounds = true;
1415        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1416        final int rotation = getRotation(file);
1417        final boolean rotated = rotation == 90 || rotation == 270;
1418        final int imageHeight = rotated ? options.outWidth : options.outHeight;
1419        final int imageWidth = rotated ? options.outHeight : options.outWidth;
1420        return new Dimensions(imageHeight, imageWidth);
1421    }
1422
1423    private Dimensions getVideoDimensions(final File file) throws NotAVideoFile, IOException {
1424        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1425        try {
1426            metadataRetriever.setDataSource(file.getAbsolutePath());
1427        } catch (RuntimeException e) {
1428            throw new NotAVideoFile(e);
1429        }
1430        return getVideoDimensions(metadataRetriever);
1431    }
1432
1433    private Dimensions getPdfDocumentDimensions(final File file) {
1434        final ParcelFileDescriptor fileDescriptor;
1435        try {
1436            fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1437            if (fileDescriptor == null) {
1438                return new Dimensions(0, 0);
1439            }
1440        } catch (final FileNotFoundException e) {
1441            return new Dimensions(0, 0);
1442        }
1443        try {
1444            final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1445            final PdfRenderer.Page page = pdfRenderer.openPage(0);
1446            final int height = page.getHeight();
1447            final int width = page.getWidth();
1448            page.close();
1449            pdfRenderer.close();
1450            return scalePdfDimensions(new Dimensions(height, width));
1451        } catch (final IOException | SecurityException e) {
1452            Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
1453            return new Dimensions(0, 0);
1454        }
1455    }
1456
1457    private Dimensions scalePdfDimensions(Dimensions in) {
1458        final DisplayMetrics displayMetrics =
1459                mXmppConnectionService.getResources().getDisplayMetrics();
1460        final int target = (int) (displayMetrics.density * 288);
1461        return scalePdfDimensions(in, target, true);
1462    }
1463
1464    private static Dimensions scalePdfDimensions(
1465            final Dimensions in, final int target, final boolean fit) {
1466        final int w, h;
1467        if (fit == (in.width <= in.height)) {
1468            w = Math.max((int) (in.width / ((double) in.height / target)), 1);
1469            h = target;
1470        } else {
1471            w = target;
1472            h = Math.max((int) (in.height / ((double) in.width / target)), 1);
1473        }
1474        return new Dimensions(h, w);
1475    }
1476
1477    public Bitmap getAvatar(String avatar, int size) {
1478        if (avatar == null) {
1479            return null;
1480        }
1481        Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1482        return bm;
1483    }
1484
1485    private static class Dimensions {
1486        public final int width;
1487        public final int height;
1488
1489        Dimensions(int height, int width) {
1490            this.width = width;
1491            this.height = height;
1492        }
1493
1494        public int getMin() {
1495            return Math.min(width, height);
1496        }
1497
1498        public boolean valid() {
1499            return width > 0 && height > 0;
1500        }
1501    }
1502
1503    private static class NotAVideoFile extends Exception {
1504        public NotAVideoFile(Throwable t) {
1505            super(t);
1506        }
1507
1508        public NotAVideoFile() {
1509            super();
1510        }
1511    }
1512
1513    public static class ImageCompressionException extends Exception {
1514
1515        ImageCompressionException(String message) {
1516            super(message);
1517        }
1518    }
1519
1520    public static class FileCopyException extends Exception {
1521        private final int resId;
1522
1523        private FileCopyException(@StringRes int resId) {
1524            this.resId = resId;
1525        }
1526
1527        public @StringRes int getResId() {
1528            return resId;
1529        }
1530    }
1531}