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