FileBackend.java

   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;
1129                        try {
1130                            image = ThumbHash.thumbHashToRGBA(data);
1131                        } catch (final Exception e) {
1132                            continue;
1133                        }
1134                        int[] pixels = new int[image.width * image.height];
1135                        for (int i = 0; i < pixels.length; i++) {
1136                            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);
1137                        }
1138                        cached = new BitmapDrawable(Bitmap.createBitmap(pixels, image.width, image.height, Bitmap.Config.ARGB_8888));
1139                        cache.put(parts[1], cached);
1140                        return cached;
1141                    }
1142                }
1143            }
1144         }
1145
1146        return null;
1147    }
1148
1149    public Drawable getThumbnail(Message message, Resources res, int size, boolean cacheOnly) throws IOException {
1150        final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
1151        DownloadableFile file = getFile(message);
1152        Drawable thumbnail = cache.get(file.getAbsolutePath());
1153        if (thumbnail != null) return thumbnail;
1154
1155        if ((thumbnail == null) && (!cacheOnly)) {
1156            synchronized (THUMBNAIL_LOCK) {
1157                List<Element> thumbs = message.getFileParams() != null ? message.getFileParams().getThumbnails() : null;
1158                if (thumbs != null && !thumbs.isEmpty()) {
1159                    for (Element thumb : thumbs) {
1160                        Uri uri = Uri.parse(thumb.getAttribute("uri"));
1161                        if (uri.getScheme().equals("data")) {
1162                            if (android.os.Build.VERSION.SDK_INT < 28) continue;
1163                            String[] parts = uri.getSchemeSpecificPart().split(",", 2);
1164
1165                            byte[] data;
1166                            if (Arrays.asList(parts[0].split(";")).contains("base64")) {
1167                                String[] parts2 = parts[0].split(";", 2);
1168                                parts[0] = parts2[0];
1169                                data = Base64.decode(parts[1], 0);
1170                            } else {
1171                                data = parts[1].getBytes("UTF-8");
1172                            }
1173
1174                            if (parts[0].equals("image/blurhash")) continue; // blurhash only for fallback
1175                            if (parts[0].equals("image/thumbhash")) continue; // thumbhash only for fallback
1176
1177                            ImageDecoder.Source source = ImageDecoder.createSource(ByteBuffer.wrap(data));
1178                            thumbnail = ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1179                                int w = info.getSize().getWidth();
1180                                int h = info.getSize().getHeight();
1181                                Rect r = rectForSize(w, h, size);
1182                                decoder.setTargetSize(r.width(), r.height());
1183                            });
1184
1185                            if (thumbnail != null) {
1186                                cache.put(file.getAbsolutePath(), thumbnail);
1187                                return thumbnail;
1188                            }
1189                        } else if (uri.getScheme().equals("cid")) {
1190                            Cid cid = BobTransfer.cid(uri);
1191                            if (cid == null) continue;
1192                            DownloadableFile f = mXmppConnectionService.getFileForCid(cid);
1193                            if (f != null && f.canRead()) {
1194                                return getThumbnail(f, res, size, cacheOnly);
1195                            }
1196                        }
1197                    }
1198                }
1199            }
1200        }
1201
1202        return getThumbnail(file, res, size, cacheOnly);
1203    }
1204
1205    public Drawable getThumbnail(DownloadableFile file, Resources res, int size, boolean cacheOnly) throws IOException {
1206        return getThumbnail(file, res, size, cacheOnly, file.getAbsolutePath());
1207    }
1208
1209    public Drawable getThumbnail(DownloadableFile file, Resources res, int size, boolean cacheOnly, String cacheKey) throws IOException {
1210        final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
1211        Drawable thumbnail = cache.get(cacheKey);
1212        if ((thumbnail == null) && (!cacheOnly)) {
1213            synchronized (THUMBNAIL_LOCK) {
1214                thumbnail = cache.get(cacheKey);
1215                if (thumbnail != null) {
1216                    return thumbnail;
1217                }
1218                final String mime = file.getMimeType();
1219                if ("application/pdf".equals(mime)) {
1220                    thumbnail = new BitmapDrawable(res, getPdfDocumentPreview(file, size));
1221                } else if (mime.startsWith("video/")) {
1222                    thumbnail = new BitmapDrawable(res, getVideoPreview(file, size));
1223                } else {
1224                    thumbnail = getImagePreview(file, res, size, mime);
1225                    if (thumbnail == null) {
1226                        throw new FileNotFoundException();
1227                    }
1228                }
1229                cache.put(cacheKey, thumbnail);
1230            }
1231        }
1232        return thumbnail;
1233    }
1234
1235    public Bitmap getThumbnailBitmap(Message message, Resources res, int size) throws IOException {
1236          final Drawable drawable = getThumbnail(message, res, size, false);
1237          if (drawable == null) return null;
1238          return drawDrawable(drawable);
1239    }
1240
1241    public Bitmap getThumbnailBitmap(DownloadableFile file, Resources res, int size, String cacheKey) throws IOException {
1242          final Drawable drawable = getThumbnail(file, res, size, false, cacheKey);
1243          if (drawable == null) return null;
1244          return drawDrawable(drawable);
1245    }
1246
1247    public static Rect rectForSize(int w, int h, int size) {
1248        int scalledW;
1249        int scalledH;
1250        if (w <= h) {
1251            scalledW = Math.max((int) (w / ((double) h / size)), 1);
1252            scalledH = size;
1253        } else {
1254            scalledW = size;
1255            scalledH = Math.max((int) (h / ((double) w / size)), 1);
1256        }
1257
1258        if (scalledW > w || scalledH > h) return new Rect(0, 0, w, h);
1259
1260        return new Rect(0, 0, scalledW, scalledH);
1261    }
1262
1263    private Drawable getImagePreview(File file, Resources res, int size, final String mime) throws IOException {
1264        if (android.os.Build.VERSION.SDK_INT >= 28) {
1265            ImageDecoder.Source source = ImageDecoder.createSource(file);
1266            return ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1267                int w = info.getSize().getWidth();
1268                int h = info.getSize().getHeight();
1269                Rect r = rectForSize(w, h, size);
1270                decoder.setTargetSize(r.width(), r.height());
1271            });
1272        } else {
1273            BitmapFactory.Options options = new BitmapFactory.Options();
1274            options.inSampleSize = calcSampleSize(file, size);
1275            Bitmap bitmap = null;
1276            try {
1277                bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1278            } catch (OutOfMemoryError e) {
1279                options.inSampleSize *= 2;
1280                bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1281            }
1282            if (bitmap == null) return null;
1283
1284            bitmap = resize(bitmap, size);
1285            bitmap = rotate(bitmap, getRotation(file));
1286            if (mime.equals("image/gif")) {
1287                Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
1288                drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
1289                bitmap.recycle();
1290                bitmap = withGifOverlay;
1291            }
1292            return new BitmapDrawable(res, bitmap);
1293        }
1294    }
1295
1296    protected Bitmap drawDrawable(Drawable drawable) {
1297        Bitmap bitmap = null;
1298
1299        if (drawable instanceof BitmapDrawable) {
1300            bitmap = ((BitmapDrawable) drawable).getBitmap();
1301            if (bitmap != null) return bitmap;
1302        }
1303
1304        bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
1305        Canvas canvas = new Canvas(bitmap);
1306        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1307        drawable.draw(canvas);
1308        return bitmap;
1309    }
1310
1311    private void drawOverlay(Bitmap bitmap, int resource, float factor) {
1312        Bitmap overlay =
1313                BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
1314        Canvas canvas = new Canvas(bitmap);
1315        float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
1316        Log.d(
1317                Config.LOGTAG,
1318                "target size overlay: "
1319                        + targetSize
1320                        + " overlay bitmap size was "
1321                        + overlay.getHeight());
1322        float left = (canvas.getWidth() - targetSize) / 2.0f;
1323        float top = (canvas.getHeight() - targetSize) / 2.0f;
1324        RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
1325        canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
1326    }
1327
1328    /** https://stackoverflow.com/a/3943023/210897 */
1329    private boolean paintOverlayBlack(final Bitmap bitmap) {
1330        final int h = bitmap.getHeight();
1331        final int w = bitmap.getWidth();
1332        int record = 0;
1333        for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
1334            for (int x = Math.round(w * IGNORE_PADDING);
1335                    x < w - Math.round(w * IGNORE_PADDING);
1336                    ++x) {
1337                int pixel = bitmap.getPixel(x, y);
1338                if ((Color.red(pixel) * 0.299
1339                                + Color.green(pixel) * 0.587
1340                                + Color.blue(pixel) * 0.114)
1341                        > 186) {
1342                    --record;
1343                } else {
1344                    ++record;
1345                }
1346            }
1347        }
1348        return record < 0;
1349    }
1350
1351    private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
1352        final int h = bitmap.getHeight();
1353        final int w = bitmap.getWidth();
1354        int white = 0;
1355        for (int y = 0; y < h; ++y) {
1356            for (int x = 0; x < w; ++x) {
1357                int pixel = bitmap.getPixel(x, y);
1358                if ((Color.red(pixel) * 0.299
1359                                + Color.green(pixel) * 0.587
1360                                + Color.blue(pixel) * 0.114)
1361                        > 186) {
1362                    white++;
1363                }
1364            }
1365        }
1366        return white > (h * w * 0.4f);
1367    }
1368
1369    private Bitmap cropCenterSquareVideo(Uri uri, int size) {
1370        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1371        Bitmap frame;
1372        try {
1373            metadataRetriever.setDataSource(mXmppConnectionService, uri);
1374            frame = metadataRetriever.getFrameAtTime(0);
1375            metadataRetriever.release();
1376            return cropCenterSquare(frame, size);
1377        } catch (Exception e) {
1378            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1379            frame.eraseColor(0xff000000);
1380            return frame;
1381        }
1382    }
1383
1384    private Bitmap getVideoPreview(final File file, final int size) {
1385        final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1386        Bitmap frame;
1387        try {
1388            metadataRetriever.setDataSource(file.getAbsolutePath());
1389            frame = metadataRetriever.getFrameAtTime(0);
1390            metadataRetriever.release();
1391            frame = resize(frame, size);
1392        } catch (IOException | RuntimeException e) {
1393            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1394            frame.eraseColor(0xff000000);
1395        }
1396        drawOverlay(
1397                frame,
1398                paintOverlayBlack(frame)
1399                        ? R.drawable.play_video_black
1400                        : R.drawable.play_video_white,
1401                0.75f);
1402        return frame;
1403    }
1404
1405    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1406    private Bitmap getPdfDocumentPreview(final File file, final int size) {
1407        try {
1408            final ParcelFileDescriptor fileDescriptor =
1409                    ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1410            final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
1411            drawOverlay(
1412                    rendered,
1413                    paintOverlayBlackPdf(rendered)
1414                            ? R.drawable.open_pdf_black
1415                            : R.drawable.open_pdf_white,
1416                    0.75f);
1417            return rendered;
1418        } catch (final IOException | SecurityException e) {
1419            Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
1420            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1421            placeholder.eraseColor(0xff000000);
1422            return placeholder;
1423        }
1424    }
1425
1426    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1427    private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
1428        try {
1429            ParcelFileDescriptor fileDescriptor =
1430                    mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
1431            final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1432            return cropCenterSquare(bitmap, size);
1433        } catch (Exception e) {
1434            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1435            placeholder.eraseColor(0xff000000);
1436            return placeholder;
1437        }
1438    }
1439
1440    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1441    private Bitmap renderPdfDocument(
1442            ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1443        final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1444        final PdfRenderer.Page page = pdfRenderer.openPage(0);
1445        final Dimensions dimensions =
1446                scalePdfDimensions(
1447                        new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1448        final Bitmap rendered =
1449                Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1450        rendered.eraseColor(0xffffffff);
1451        page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1452        page.close();
1453        pdfRenderer.close();
1454        fileDescriptor.close();
1455        return rendered;
1456    }
1457
1458    public Uri getTakePhotoUri() {
1459        final String filename =
1460                String.format("IMG_%s.%s", IMAGE_DATE_FORMAT.format(new Date()), "jpg");
1461        final File directory;
1462        if (Config.ONLY_INTERNAL_STORAGE) {
1463            directory = new File(mXmppConnectionService.getCacheDir(), "Camera");
1464        } else {
1465            directory =
1466                    new File(
1467                            Environment.getExternalStoragePublicDirectory(
1468                                    Environment.DIRECTORY_DCIM),
1469                            "Camera");
1470        }
1471        final File file = new File(directory, filename);
1472        file.getParentFile().mkdirs();
1473        return getUriForFile(mXmppConnectionService, file);
1474    }
1475
1476    public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
1477
1478        final Avatar uncompressAvatar = getUncompressedAvatar(image);
1479        if (uncompressAvatar != null
1480                && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
1481            return uncompressAvatar;
1482        }
1483        if (uncompressAvatar != null) {
1484            Log.d(
1485                    Config.LOGTAG,
1486                    "uncompressed avatar exceeded char limit by "
1487                            + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
1488        }
1489
1490        Bitmap bm = cropCenterSquare(image, size);
1491        if (bm == null) {
1492            return null;
1493        }
1494        if (hasAlpha(bm)) {
1495            Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
1496            bm.recycle();
1497            bm = cropCenterSquare(image, 96);
1498            return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
1499        }
1500        return getPepAvatar(bm, format, 100);
1501    }
1502
1503    private Avatar getUncompressedAvatar(Uri uri) {
1504        Bitmap bitmap = null;
1505        try {
1506            bitmap =
1507                    BitmapFactory.decodeStream(
1508                            mXmppConnectionService.getContentResolver().openInputStream(uri));
1509            return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
1510        } catch (Exception e) {
1511            return null;
1512        } finally {
1513            if (bitmap != null) {
1514                bitmap.recycle();
1515            }
1516        }
1517    }
1518
1519    private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1520        try {
1521            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1522            Base64OutputStream mBase64OutputStream =
1523                    new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1524            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1525            DigestOutputStream mDigestOutputStream =
1526                    new DigestOutputStream(mBase64OutputStream, digest);
1527            if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1528                return null;
1529            }
1530            mDigestOutputStream.flush();
1531            mDigestOutputStream.close();
1532            long chars = mByteArrayOutputStream.size();
1533            if (format != Bitmap.CompressFormat.PNG
1534                    && quality >= 50
1535                    && chars >= Config.AVATAR_CHAR_LIMIT) {
1536                int q = quality - 2;
1537                Log.d(
1538                        Config.LOGTAG,
1539                        "avatar char length was " + chars + " reducing quality to " + q);
1540                return getPepAvatar(bitmap, format, q);
1541            }
1542            Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1543            final Avatar avatar = new Avatar();
1544            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1545            avatar.image = new String(mByteArrayOutputStream.toByteArray());
1546            if (format.equals(Bitmap.CompressFormat.WEBP)) {
1547                avatar.type = "image/webp";
1548            } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1549                avatar.type = "image/jpeg";
1550            } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1551                avatar.type = "image/png";
1552            }
1553            avatar.width = bitmap.getWidth();
1554            avatar.height = bitmap.getHeight();
1555            return avatar;
1556        } catch (OutOfMemoryError e) {
1557            Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1558            return null;
1559        } catch (Exception e) {
1560            return null;
1561        }
1562    }
1563
1564    public Avatar getStoredPepAvatar(String hash) {
1565        if (hash == null) {
1566            return null;
1567        }
1568        Avatar avatar = new Avatar();
1569        final File file = getAvatarFile(hash);
1570        FileInputStream is = null;
1571        try {
1572            avatar.size = file.length();
1573            BitmapFactory.Options options = new BitmapFactory.Options();
1574            options.inJustDecodeBounds = true;
1575            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1576            is = new FileInputStream(file);
1577            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1578            Base64OutputStream mBase64OutputStream =
1579                    new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1580            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1581            DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1582            byte[] buffer = new byte[4096];
1583            int length;
1584            while ((length = is.read(buffer)) > 0) {
1585                os.write(buffer, 0, length);
1586            }
1587            os.flush();
1588            os.close();
1589            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1590            avatar.image = new String(mByteArrayOutputStream.toByteArray());
1591            avatar.height = options.outHeight;
1592            avatar.width = options.outWidth;
1593            avatar.type = options.outMimeType;
1594            return avatar;
1595        } catch (NoSuchAlgorithmException | IOException e) {
1596            return null;
1597        } finally {
1598            close(is);
1599        }
1600    }
1601
1602    public boolean isAvatarCached(Avatar avatar) {
1603        final File file = getAvatarFile(avatar.getFilename());
1604        return file.exists();
1605    }
1606
1607    public boolean save(final Avatar avatar) {
1608        File file;
1609        if (isAvatarCached(avatar)) {
1610            file = getAvatarFile(avatar.getFilename());
1611            avatar.size = file.length();
1612        } else {
1613            file =
1614                    new File(
1615                            mXmppConnectionService.getCacheDir().getAbsolutePath()
1616                                    + "/"
1617                                    + UUID.randomUUID().toString());
1618            if (file.getParentFile().mkdirs()) {
1619                Log.d(Config.LOGTAG, "created cache directory");
1620            }
1621            OutputStream os = null;
1622            try {
1623                if (!file.createNewFile()) {
1624                    Log.d(
1625                            Config.LOGTAG,
1626                            "unable to create temporary file " + file.getAbsolutePath());
1627                }
1628                os = new FileOutputStream(file);
1629                MessageDigest digest = MessageDigest.getInstance("SHA-1");
1630                digest.reset();
1631                DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1632                final byte[] bytes = avatar.getImageAsBytes();
1633                mDigestOutputStream.write(bytes);
1634                mDigestOutputStream.flush();
1635                mDigestOutputStream.close();
1636                String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1637                if (sha1sum.equals(avatar.sha1sum)) {
1638                    final File outputFile = getAvatarFile(avatar.getFilename());
1639                    if (outputFile.getParentFile().mkdirs()) {
1640                        Log.d(Config.LOGTAG, "created avatar directory");
1641                    }
1642                    final File avatarFile = getAvatarFile(avatar.getFilename());
1643                    if (!file.renameTo(avatarFile)) {
1644                        Log.d(
1645                                Config.LOGTAG,
1646                                "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1647                        return false;
1648                    }
1649                } else {
1650                    Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1651                    if (!file.delete()) {
1652                        Log.d(Config.LOGTAG, "unable to delete temporary file");
1653                    }
1654                    return false;
1655                }
1656                avatar.size = bytes.length;
1657            } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1658                return false;
1659            } finally {
1660                close(os);
1661            }
1662        }
1663        return true;
1664    }
1665
1666    public void deleteHistoricAvatarPath() {
1667        delete(getHistoricAvatarPath());
1668    }
1669
1670    private void delete(final File file) {
1671        if (file.isDirectory()) {
1672            final File[] files = file.listFiles();
1673            if (files != null) {
1674                for (final File f : files) {
1675                    delete(f);
1676                }
1677            }
1678        }
1679        if (file.delete()) {
1680            Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1681        }
1682    }
1683
1684    private File getHistoricAvatarPath() {
1685        return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1686    }
1687
1688    public File getAvatarFile(String avatar) {
1689        return new File(mXmppConnectionService.getCacheDir(), "/avatars/" + avatar);
1690    }
1691
1692    public Uri getAvatarUri(String avatar) {
1693        return Uri.fromFile(getAvatarFile(avatar));
1694    }
1695
1696    public Bitmap cropCenterSquare(Uri image, int size) {
1697        if (image == null) {
1698            return null;
1699        }
1700        InputStream is = null;
1701        try {
1702            BitmapFactory.Options options = new BitmapFactory.Options();
1703            options.inSampleSize = calcSampleSize(image, size);
1704            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1705            if (is == null) {
1706                return null;
1707            }
1708            Bitmap input = BitmapFactory.decodeStream(is, null, options);
1709            if (input == null) {
1710                return null;
1711            } else {
1712                input = rotate(input, getRotation(image));
1713                return cropCenterSquare(input, size);
1714            }
1715        } catch (FileNotFoundException | SecurityException e) {
1716            Log.d(Config.LOGTAG, "unable to open file " + image.toString(), e);
1717            return null;
1718        } finally {
1719            close(is);
1720        }
1721    }
1722
1723    public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1724        if (image == null) {
1725            return null;
1726        }
1727        InputStream is = null;
1728        try {
1729            BitmapFactory.Options options = new BitmapFactory.Options();
1730            options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1731            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1732            if (is == null) {
1733                return null;
1734            }
1735            Bitmap source = BitmapFactory.decodeStream(is, null, options);
1736            if (source == null) {
1737                return null;
1738            }
1739            int sourceWidth = source.getWidth();
1740            int sourceHeight = source.getHeight();
1741            float xScale = (float) newWidth / sourceWidth;
1742            float yScale = (float) newHeight / sourceHeight;
1743            float scale = Math.max(xScale, yScale);
1744            float scaledWidth = scale * sourceWidth;
1745            float scaledHeight = scale * sourceHeight;
1746            float left = (newWidth - scaledWidth) / 2;
1747            float top = (newHeight - scaledHeight) / 2;
1748
1749            RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1750            Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1751            Canvas canvas = new Canvas(dest);
1752            canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1753            if (source.isRecycled()) {
1754                source.recycle();
1755            }
1756            return dest;
1757        } catch (SecurityException e) {
1758            return null; // android 6.0 with revoked permissions for example
1759        } catch (FileNotFoundException e) {
1760            return null;
1761        } finally {
1762            close(is);
1763        }
1764    }
1765
1766    public Bitmap cropCenterSquare(Bitmap input, int size) {
1767        int w = input.getWidth();
1768        int h = input.getHeight();
1769
1770        float scale = Math.max((float) size / h, (float) size / w);
1771
1772        float outWidth = scale * w;
1773        float outHeight = scale * h;
1774        float left = (size - outWidth) / 2;
1775        float top = (size - outHeight) / 2;
1776        RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1777
1778        Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1779        Canvas canvas = new Canvas(output);
1780        canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1781        if (!input.isRecycled()) {
1782            input.recycle();
1783        }
1784        return output;
1785    }
1786
1787    private int calcSampleSize(Uri image, int size)
1788            throws FileNotFoundException, SecurityException {
1789        final BitmapFactory.Options options = new BitmapFactory.Options();
1790        options.inJustDecodeBounds = true;
1791        final InputStream inputStream =
1792                mXmppConnectionService.getContentResolver().openInputStream(image);
1793        BitmapFactory.decodeStream(inputStream, null, options);
1794        close(inputStream);
1795        return calcSampleSize(options, size);
1796    }
1797
1798    public void updateFileParams(Message message) {
1799        updateFileParams(message, null);
1800    }
1801
1802    public void updateFileParams(final Message message, final String url) {
1803        updateFileParams(message, url, true);
1804    }
1805
1806    public void updateFileParams(final Message message, String url, boolean updateCids) {
1807        final boolean encrypted =
1808                message.getEncryption() == Message.ENCRYPTION_PGP
1809                        || message.getEncryption() == Message.ENCRYPTION_DECRYPTED;
1810        final DownloadableFile file = getFile(message);
1811        final String mime = file.getMimeType();
1812        final boolean privateMessage = message.isPrivateMessage();
1813        final boolean image =
1814                message.getType() == Message.TYPE_IMAGE
1815                        || (mime != null && mime.startsWith("image/"));
1816        Message.FileParams fileParams = message.getFileParams();
1817        if (fileParams == null) fileParams = new Message.FileParams();
1818        Cid[] cids = new Cid[0];
1819        try {
1820            cids = calculateCids(new FileInputStream(file));
1821            fileParams.setCids(List.of(cids));
1822        } catch (final IOException | NoSuchAlgorithmException e) { }
1823        if (url == null) {
1824            for (Cid cid : cids) {
1825                url = mXmppConnectionService.getUrlForCid(cid);
1826                if (url != null) {
1827                    fileParams.url = url;
1828                    break;
1829                }
1830            }
1831        } else {
1832            fileParams.url = url;
1833        }
1834        if (fileParams.getName() == null) fileParams.setName(file.getName());
1835        fileParams.setMediaType(mime);
1836        if (encrypted && !file.exists()) {
1837            Log.d(Config.LOGTAG, "skipping updateFileParams because file is encrypted");
1838            final DownloadableFile encryptedFile = getFile(message, false);
1839            fileParams.size = encryptedFile.getSize();
1840        } else {
1841            Log.d(Config.LOGTAG, "running updateFileParams");
1842            final boolean ambiguous = MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime);
1843            final boolean video = mime != null && mime.startsWith("video/");
1844            final boolean audio = mime != null && mime.startsWith("audio/");
1845            final boolean pdf = "application/pdf".equals(mime);
1846            fileParams.size = file.getSize();
1847            if (ambiguous) {
1848                try {
1849                    final Dimensions dimensions = getVideoDimensions(file);
1850                    if (dimensions.valid()) {
1851                        Log.d(Config.LOGTAG, "ambiguous file " + mime + " is video");
1852                        fileParams.width = dimensions.width;
1853                        fileParams.height = dimensions.height;
1854                    } else {
1855                        Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1856                        fileParams.runtime = getMediaRuntime(file);
1857                    }
1858                } catch (final NotAVideoFile e) {
1859                    Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1860                    fileParams.runtime = getMediaRuntime(file);
1861                }
1862            } else if (image || video || pdf) {
1863                try {
1864                    final Dimensions dimensions;
1865                    if (video) {
1866                        dimensions = getVideoDimensions(file);
1867                    } else if (pdf) {
1868                        dimensions = getPdfDocumentDimensions(file);
1869                    } else {
1870                        dimensions = getImageDimensions(file);
1871                    }
1872                    if (dimensions.valid()) {
1873                        fileParams.width = dimensions.width;
1874                        fileParams.height = dimensions.height;
1875                    }
1876                } catch (NotAVideoFile notAVideoFile) {
1877                    Log.d(
1878                            Config.LOGTAG,
1879                            "file with mime type " + file.getMimeType() + " was not a video file");
1880                    // fall threw
1881                }
1882            } else if (audio) {
1883                fileParams.runtime = getMediaRuntime(file);
1884            }
1885            try {
1886                Bitmap thumb = getThumbnailBitmap(file, mXmppConnectionService.getResources(), 100, file.getAbsolutePath() + " x 100");
1887                if (thumb != null) {
1888                    int[] pixels = new int[thumb.getWidth() * thumb.getHeight()];
1889                    byte[] rgba = new byte[pixels.length * 4];
1890                    try {
1891                        thumb.getPixels(pixels, 0, thumb.getWidth(), 0, 0, thumb.getWidth(), thumb.getHeight());
1892                    } catch (final IllegalStateException e) {
1893                        Bitmap softThumb = thumb.copy(Bitmap.Config.ARGB_8888, false);
1894                        softThumb.getPixels(pixels, 0, thumb.getWidth(), 0, 0, thumb.getWidth(), thumb.getHeight());
1895                        softThumb.recycle();
1896                    }
1897                    for (int i = 0; i < pixels.length; i++) {
1898                        rgba[i*4] = (byte)((pixels[i] >> 16) & 0xff);
1899                        rgba[(i*4)+1] = (byte)((pixels[i] >> 8) & 0xff);
1900                        rgba[(i*4)+2] = (byte)(pixels[i] & 0xff);
1901                        rgba[(i*4)+3] = (byte)((pixels[i] >> 24) & 0xff);
1902                    }
1903                    fileParams.addThumbnail(thumb.getWidth(), thumb.getHeight(), "image/thumbhash", "data:image/thumbhash;base64," + Base64.encodeToString(ThumbHash.rgbaToThumbHash(thumb.getWidth(), thumb.getHeight(), rgba), Base64.NO_WRAP));
1904                }
1905            } catch (final IOException e) { }
1906        }
1907        message.setFileParams(fileParams);
1908        message.setDeleted(false);
1909        message.setType(
1910                privateMessage
1911                        ? Message.TYPE_PRIVATE_FILE
1912                        : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
1913
1914        if (updateCids) {
1915            try {
1916                for (int i = 0; i < cids.length; i++) {
1917                    mXmppConnectionService.saveCid(cids[i], file);
1918                }
1919            } catch (XmppConnectionService.BlockedMediaException e) { }
1920        }
1921    }
1922
1923    private int getMediaRuntime(final File file) {
1924        try {
1925            final MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1926            mediaMetadataRetriever.setDataSource(file.toString());
1927            final String value =
1928                    mediaMetadataRetriever.extractMetadata(
1929                            MediaMetadataRetriever.METADATA_KEY_DURATION);
1930            if (Strings.isNullOrEmpty(value)) {
1931                return 0;
1932            }
1933            return Integer.parseInt(value);
1934        } catch (final Exception e) {
1935            return 0;
1936        }
1937    }
1938
1939    private Dimensions getImageDimensions(File file) {
1940        final BitmapFactory.Options options = new BitmapFactory.Options();
1941        options.inJustDecodeBounds = true;
1942        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1943        final int rotation = getRotation(file);
1944        final boolean rotated = rotation == 90 || rotation == 270;
1945        final int imageHeight = rotated ? options.outWidth : options.outHeight;
1946        final int imageWidth = rotated ? options.outHeight : options.outWidth;
1947        return new Dimensions(imageHeight, imageWidth);
1948    }
1949
1950    private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1951        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1952        try {
1953            metadataRetriever.setDataSource(file.getAbsolutePath());
1954        } catch (RuntimeException e) {
1955            throw new NotAVideoFile(e);
1956        }
1957        return getVideoDimensions(metadataRetriever);
1958    }
1959
1960    private Dimensions getPdfDocumentDimensions(final File file) {
1961        final ParcelFileDescriptor fileDescriptor;
1962        try {
1963            fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1964            if (fileDescriptor == null) {
1965                return new Dimensions(0, 0);
1966            }
1967        } catch (final FileNotFoundException e) {
1968            return new Dimensions(0, 0);
1969        }
1970        try {
1971            final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1972            final PdfRenderer.Page page = pdfRenderer.openPage(0);
1973            final int height = page.getHeight();
1974            final int width = page.getWidth();
1975            page.close();
1976            pdfRenderer.close();
1977            return scalePdfDimensions(new Dimensions(height, width));
1978        } catch (final IOException | SecurityException e) {
1979            Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
1980            return new Dimensions(0, 0);
1981        }
1982    }
1983
1984    private Dimensions scalePdfDimensions(Dimensions in) {
1985        final DisplayMetrics displayMetrics =
1986                mXmppConnectionService.getResources().getDisplayMetrics();
1987        final int target = (int) (displayMetrics.density * 288);
1988        return scalePdfDimensions(in, target, true);
1989    }
1990
1991    private static Dimensions scalePdfDimensions(
1992            final Dimensions in, final int target, final boolean fit) {
1993        final int w, h;
1994        if (fit == (in.width <= in.height)) {
1995            w = Math.max((int) (in.width / ((double) in.height / target)), 1);
1996            h = target;
1997        } else {
1998            w = target;
1999            h = Math.max((int) (in.height / ((double) in.width / target)), 1);
2000        }
2001        return new Dimensions(h, w);
2002    }
2003
2004    public Bitmap getAvatar(String avatar, int size) {
2005        if (avatar == null) {
2006            return null;
2007        }
2008        Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
2009        return bm;
2010    }
2011
2012    private static class Dimensions {
2013        public final int width;
2014        public final int height;
2015
2016        Dimensions(int height, int width) {
2017            this.width = width;
2018            this.height = height;
2019        }
2020
2021        public int getMin() {
2022            return Math.min(width, height);
2023        }
2024
2025        public boolean valid() {
2026            return width > 0 && height > 0;
2027        }
2028    }
2029
2030    private static class NotAVideoFile extends Exception {
2031        public NotAVideoFile(Throwable t) {
2032            super(t);
2033        }
2034
2035        public NotAVideoFile() {
2036            super();
2037        }
2038    }
2039
2040    public static class ImageCompressionException extends Exception {
2041
2042        ImageCompressionException(String message) {
2043            super(message);
2044        }
2045    }
2046
2047    public static class FileCopyException extends Exception {
2048        private final int resId;
2049
2050        private FileCopyException(@StringRes int resId) {
2051            this.resId = resId;
2052        }
2053
2054        public @StringRes int getResId() {
2055            return resId;
2056        }
2057    }
2058}