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