FileBackend.java

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