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