FileBackend.java

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