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 IllegalArgumentException e) {
 753            throw new FileCopyException(R.string.error_file_not_found);
 754        } catch (final FileNotFoundException e) {
 755            throw new FileCopyException(R.string.error_file_not_found);
 756        } catch (final FileWriterException e) {
 757            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 758        } catch (final SecurityException | IllegalStateException e) {
 759            throw new FileCopyException(R.string.error_security_exception);
 760        } catch (final IOException e) {
 761            throw new FileCopyException(R.string.error_io_exception);
 762        }
 763    }
 764
 765    private InputStream openInputStream(Uri uri) throws IOException {
 766        if (uri != null && "data".equals(uri.getScheme())) {
 767            String[] parts = uri.getSchemeSpecificPart().split(",", 2);
 768            byte[] data;
 769            if (Arrays.asList(parts[0].split(";")).contains("base64")) {
 770                String[] parts2 = parts[0].split(";", 2);
 771                parts[0] = parts2[0];
 772                data = Base64.decode(parts[1], 0);
 773            } else {
 774                try {
 775                    data = parts[1].getBytes("UTF-8");
 776                } catch (final IOException e) {
 777                    data = new byte[0];
 778                }
 779            }
 780            return new ByteArrayInputStream(data);
 781        }
 782        final InputStream is = mXmppConnectionService.getContentResolver().openInputStream(uri);
 783        if (is == null) throw new FileNotFoundException("File not found");
 784        return is;
 785    }
 786
 787    private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
 788        final var parentDirectory = file.getParentFile();
 789        if (parentDirectory != null && parentDirectory.mkdirs()) {
 790            Log.d(Config.LOGTAG,"created directory "+parentDirectory.getAbsolutePath());
 791        }
 792        try {
 793            if (!file.createNewFile() && file.length() > 0) {
 794                if (file.canRead() && file.getName().startsWith("zb2")) return; // We have this content already
 795                throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 796            }
 797        } catch (final IOException e) {
 798            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 799        }
 800        try (final OutputStream os = new FileOutputStream(file);
 801                final InputStream is = openInputStream(uri)) {
 802            if (is == null) {
 803                throw new FileCopyException(R.string.error_file_not_found);
 804            }
 805            try {
 806                ByteStreams.copy(is, os);
 807            } catch (final IOException e) {
 808                throw new FileWriterException(file);
 809            }
 810            try {
 811                os.flush();
 812            } catch (final IOException e) {
 813                throw new FileWriterException(file);
 814            }
 815        } catch (final FileNotFoundException e) {
 816            cleanup(file);
 817            throw new FileCopyException(R.string.error_file_not_found);
 818        } catch (final FileWriterException e) {
 819            cleanup(file);
 820            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 821        } catch (final SecurityException | IllegalStateException | IllegalArgumentException e) {
 822            cleanup(file);
 823            throw new FileCopyException(R.string.error_security_exception);
 824        } catch (final IOException e) {
 825            cleanup(file);
 826            throw new FileCopyException(R.string.error_io_exception);
 827        }
 828    }
 829
 830    public void copyFileToPrivateStorage(Message message, Uri uri, String type)
 831            throws FileCopyException {
 832        final String mime = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
 833        Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
 834        String extension = MimeUtils.guessExtensionFromMimeType(mime);
 835        if (extension == null) {
 836            Log.d(Config.LOGTAG, "extension from mime type was null");
 837            extension = getExtensionFromUri(uri);
 838        }
 839        if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
 840            extension = "oga";
 841        }
 842
 843        try {
 844            setupRelativeFilePath(message, uri, extension);
 845            copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
 846            final String name = getDisplayNameFromUri(uri);
 847            if (name != null) {
 848                message.getFileParams().setName(name);
 849            }
 850        } catch (final XmppConnectionService.BlockedMediaException e) {
 851            message.setRelativeFilePath(null);
 852            message.setDeleted(true);
 853        }
 854    }
 855
 856    private String getDisplayNameFromUri(final Uri uri) {
 857        final String[] projection = {OpenableColumns.DISPLAY_NAME};
 858        String filename = null;
 859        try (final Cursor cursor =
 860                mXmppConnectionService
 861                        .getContentResolver()
 862                        .query(uri, projection, null, null, null)) {
 863            if (cursor != null && cursor.moveToFirst()) {
 864                filename = cursor.getString(0);
 865            }
 866        } catch (final Exception e) {
 867            filename = null;
 868        }
 869        return filename;
 870    }
 871
 872    private String getExtensionFromUri(final Uri uri) {
 873        final String[] projection = {MediaStore.MediaColumns.DATA};
 874        String filename = null;
 875        try (final Cursor cursor =
 876                mXmppConnectionService
 877                        .getContentResolver()
 878                        .query(uri, projection, null, null, null)) {
 879            if (cursor != null && cursor.moveToFirst()) {
 880                filename = cursor.getString(0);
 881            }
 882        } catch (final Exception e) {
 883            filename = null;
 884        }
 885        if (filename == null) {
 886            final List<String> segments = uri.getPathSegments();
 887            if (segments.size() > 0) {
 888                filename = segments.get(segments.size() - 1);
 889            }
 890        }
 891        final int pos = filename == null ? -1 : filename.lastIndexOf('.');
 892        return pos > 0 ? filename.substring(pos + 1) : null;
 893    }
 894
 895    private void copyImageToPrivateStorage(File file, Uri image, int sampleSize)
 896            throws FileCopyException, ImageCompressionException {
 897        final File parent = file.getParentFile();
 898        if (parent != null && parent.mkdirs()) {
 899            Log.d(Config.LOGTAG, "created parent directory");
 900        }
 901        InputStream is = null;
 902        OutputStream os = null;
 903        try {
 904            if (!file.exists() && !file.createNewFile()) {
 905                throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 906            }
 907            is = mXmppConnectionService.getContentResolver().openInputStream(image);
 908            if (is == null) {
 909                throw new FileCopyException(R.string.error_not_an_image_file);
 910            }
 911            final Bitmap originalBitmap;
 912            final BitmapFactory.Options options = new BitmapFactory.Options();
 913            final int inSampleSize = (int) Math.pow(2, sampleSize);
 914            Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
 915            options.inSampleSize = inSampleSize;
 916            originalBitmap = BitmapFactory.decodeStream(is, null, options);
 917            is.close();
 918            if (originalBitmap == null) {
 919                throw new ImageCompressionException("Source file was not an image");
 920            }
 921            if (!"image/jpeg".equals(options.outMimeType) && hasAlpha(originalBitmap)) {
 922                originalBitmap.recycle();
 923                throw new ImageCompressionException("Source file had alpha channel");
 924            }
 925            Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
 926            final int rotation = getRotation(image);
 927            scaledBitmap = rotate(scaledBitmap, rotation);
 928            boolean targetSizeReached = false;
 929            int quality = Config.IMAGE_QUALITY;
 930            final int imageMaxSize =
 931                    mXmppConnectionService
 932                            .getResources()
 933                            .getInteger(R.integer.auto_accept_filesize);
 934            while (!targetSizeReached) {
 935                os = new FileOutputStream(file);
 936                Log.d(Config.LOGTAG, "compressing image with quality " + quality);
 937                boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
 938                if (!success) {
 939                    throw new FileCopyException(R.string.error_compressing_image);
 940                }
 941                os.flush();
 942                final long fileSize = file.length();
 943                Log.d(Config.LOGTAG, "achieved file size of " + fileSize);
 944                targetSizeReached = fileSize <= imageMaxSize || quality <= 50;
 945                quality -= 5;
 946            }
 947            scaledBitmap.recycle();
 948        } catch (final FileNotFoundException e) {
 949            cleanup(file);
 950            throw new FileCopyException(R.string.error_file_not_found);
 951        } catch (final IOException e) {
 952            cleanup(file);
 953            throw new FileCopyException(R.string.error_io_exception);
 954        } catch (SecurityException e) {
 955            cleanup(file);
 956            throw new FileCopyException(R.string.error_security_exception_during_image_copy);
 957        } catch (final OutOfMemoryError e) {
 958            ++sampleSize;
 959            if (sampleSize <= 3) {
 960                copyImageToPrivateStorage(file, image, sampleSize);
 961            } else {
 962                throw new FileCopyException(R.string.error_out_of_memory);
 963            }
 964        } finally {
 965            close(os);
 966            close(is);
 967        }
 968    }
 969
 970    private static void cleanup(final File file) {
 971        try {
 972            file.delete();
 973        } catch (Exception e) {
 974
 975        }
 976    }
 977
 978    public void copyImageToPrivateStorage(File file, Uri image)
 979            throws FileCopyException, ImageCompressionException {
 980        Log.d(
 981                Config.LOGTAG,
 982                "copy image ("
 983                        + image.toString()
 984                        + ") to private storage "
 985                        + file.getAbsolutePath());
 986        copyImageToPrivateStorage(file, image, 0);
 987    }
 988
 989    public void copyImageToPrivateStorage(Message message, Uri image)
 990            throws FileCopyException, ImageCompressionException {
 991        final String filename;
 992        switch (Config.IMAGE_FORMAT) {
 993            case JPEG:
 994                filename = String.format("%s.%s", message.getUuid(), "jpg");
 995                break;
 996            case PNG:
 997                filename = String.format("%s.%s", message.getUuid(), "png");
 998                break;
 999            case WEBP:
1000                filename = String.format("%s.%s", message.getUuid(), "webp");
1001                break;
1002            default:
1003                throw new IllegalStateException("Unknown image format");
1004        }
1005        setupRelativeFilePath(message, filename);
1006        final File tmp = getFile(message);
1007        copyImageToPrivateStorage(tmp, image);
1008        final String extension = MimeUtils.extractRelevantExtension(filename);
1009        try {
1010            setupRelativeFilePath(message, new FileInputStream(tmp), extension);
1011        } catch (final FileNotFoundException e) {
1012            throw new FileCopyException(R.string.error_file_not_found);
1013        } catch (final IOException e) {
1014            throw new FileCopyException(R.string.error_io_exception);
1015        } catch (final XmppConnectionService.BlockedMediaException e) {
1016            tmp.delete();
1017            message.setRelativeFilePath(null);
1018            message.setDeleted(true);
1019            return;
1020        }
1021        tmp.renameTo(getFile(message));
1022        updateFileParams(message, null, false);
1023    }
1024
1025    public void setupRelativeFilePath(final Message message, final Uri uri, final String extension) throws FileCopyException, XmppConnectionService.BlockedMediaException {
1026        try {
1027            setupRelativeFilePath(message, openInputStream(uri), extension);
1028        } catch (final FileNotFoundException e) {
1029            throw new FileCopyException(R.string.error_file_not_found);
1030        } catch (final IOException e) {
1031            throw new FileCopyException(R.string.error_io_exception);
1032        }
1033    }
1034
1035    public Cid[] calculateCids(final Uri uri) throws IOException {
1036        return calculateCids(mXmppConnectionService.getContentResolver().openInputStream(uri));
1037    }
1038
1039    public Cid[] calculateCids(final InputStream is) throws IOException {
1040        try {
1041            return CryptoHelper.cid(is, new String[]{"SHA-256", "SHA-1", "SHA-512"});
1042        } catch (final NoSuchAlgorithmException e) {
1043            throw new AssertionError(e);
1044        }
1045    }
1046
1047    public void setupRelativeFilePath(final Message message, final InputStream is, final String extension) throws IOException, XmppConnectionService.BlockedMediaException {
1048        message.setRelativeFilePath(getStorageLocation(message, is, extension).getAbsolutePath());
1049    }
1050
1051    public void setupRelativeFilePath(final Message message, final String filename) {
1052        final String extension = MimeUtils.extractRelevantExtension(filename);
1053        final String mime = MimeUtils.guessMimeTypeFromExtension(extension);
1054        setupRelativeFilePath(message, filename, mime);
1055    }
1056
1057    public File getStorageLocation(final Message message, final InputStream is, final String extension) throws IOException, XmppConnectionService.BlockedMediaException {
1058        final String mime = MimeUtils.guessMimeTypeFromExtension(extension);
1059        Cid[] cids = calculateCids(is);
1060        String base = cids[0].toString();
1061
1062        File file = null;
1063        while (file == null || (file.exists() && !file.canRead())) {
1064            file = getStorageLocation(message, String.format("%s.%s", base, extension), mime);
1065            base += "_";
1066        }
1067        for (int i = 0; i < cids.length; i++) {
1068            mXmppConnectionService.saveCid(cids[i], file);
1069        }
1070        return file;
1071    }
1072
1073    public File getStorageLocation(final Message message, final String filename, final String mime) {
1074        final File parentDirectory;
1075        if (Strings.isNullOrEmpty(mime)) {
1076            parentDirectory =
1077                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
1078        } else if (mime.startsWith("image/")) {
1079            parentDirectory =
1080                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
1081        } else if (mime.startsWith("video/")) {
1082            parentDirectory =
1083                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
1084        } else if (MediaAdapter.DOCUMENT_MIMES.contains(mime)) {
1085            parentDirectory =
1086                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
1087        } else {
1088            parentDirectory =
1089                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
1090        }
1091        final File appDirectory =
1092                new File(parentDirectory, mXmppConnectionService.getString(R.string.app_name));
1093        if (message == null || message.getStatus() == Message.STATUS_DUMMY || (message.getConversation() instanceof Conversation && ((Conversation) message.getConversation()).storeInCache())) {
1094            final var mediaCache = new File(mXmppConnectionService.getCacheDir(), "/media");
1095            return new File(mediaCache, filename);
1096        } else {
1097            return new File(appDirectory, filename);
1098        }
1099    }
1100
1101    public static boolean inConversationsDirectory(final Context context, String path) {
1102        final File fileDirectory = new File(path).getParentFile();
1103        for (final String type : STORAGE_TYPES) {
1104            final File typeDirectory =
1105                    new File(
1106                            Environment.getExternalStoragePublicDirectory(type),
1107                            context.getString(R.string.app_name));
1108            if (typeDirectory.equals(fileDirectory)) {
1109                return true;
1110            }
1111        }
1112        return false;
1113    }
1114
1115    public void setupRelativeFilePath(
1116            final Message message, final String filename, final String mime) {
1117        final File file = getStorageLocation(message, filename, mime);
1118        message.setRelativeFilePath(file.getAbsolutePath());
1119    }
1120
1121    public boolean unusualBounds(final Uri image) {
1122        try {
1123            final BitmapFactory.Options options = new BitmapFactory.Options();
1124            options.inJustDecodeBounds = true;
1125            final InputStream inputStream =
1126                    mXmppConnectionService.getContentResolver().openInputStream(image);
1127            BitmapFactory.decodeStream(inputStream, null, options);
1128            close(inputStream);
1129            float ratio = (float) options.outHeight / options.outWidth;
1130            return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
1131        } catch (final Exception e) {
1132            Log.w(Config.LOGTAG, "unable to detect image bounds", e);
1133            return false;
1134        }
1135    }
1136
1137    private int getRotation(final File file) {
1138        try (final InputStream inputStream = new FileInputStream(file)) {
1139            return getRotation(inputStream);
1140        } catch (Exception e) {
1141            return 0;
1142        }
1143    }
1144
1145    private int getRotation(final Uri image) {
1146        try (final InputStream is =
1147                mXmppConnectionService.getContentResolver().openInputStream(image)) {
1148            return is == null ? 0 : getRotation(is);
1149        } catch (final Exception e) {
1150            return 0;
1151        }
1152    }
1153
1154    private static int getRotation(final InputStream inputStream) throws IOException {
1155        final ExifInterface exif = new ExifInterface(inputStream);
1156        final int orientation =
1157                exif.getAttributeInt(
1158                        ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
1159        switch (orientation) {
1160            case ExifInterface.ORIENTATION_ROTATE_180:
1161                return 180;
1162            case ExifInterface.ORIENTATION_ROTATE_90:
1163                return 90;
1164            case ExifInterface.ORIENTATION_ROTATE_270:
1165                return 270;
1166            default:
1167                return 0;
1168        }
1169    }
1170
1171    public BitmapDrawable getFallbackThumbnail(final Message message, int size, boolean cacheOnly) {
1172        final var thumbs = message.getFileParams() != null ? message.getFileParams().getThumbnails() : null;
1173        if (thumbs != null && !thumbs.isEmpty()) {
1174            for (final var thumb : thumbs) {
1175                final var uriS = thumb.getAttribute("uri");
1176                if (uriS == null) continue;
1177                Uri uri = Uri.parse(uriS);
1178                if (uri.getScheme().equals("data")) {
1179                    String[] parts = uri.getSchemeSpecificPart().split(",", 2);
1180
1181                    final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
1182                    BitmapDrawable cached = (BitmapDrawable) cache.get(parts[1]);
1183                    if (cached != null || cacheOnly) return cached;
1184
1185                    byte[] data;
1186                    if (Arrays.asList(parts[0].split(";")).contains("base64")) {
1187                        String[] parts2 = parts[0].split(";", 2);
1188                        parts[0] = parts2[0];
1189                        data = Base64.decode(parts[1], 0);
1190                    } else {
1191                        try {
1192                            data = parts[1].getBytes("UTF-8");
1193                        } catch (final IOException e) {
1194                            data = new byte[0];
1195                        }
1196                    }
1197
1198                    if (parts[0].equals("image/blurhash")) {
1199                        int width = message.getFileParams().width;
1200                        if (width < 1 && thumb.getAttribute("width") != null) width = Integer.parseInt(thumb.getAttribute("width"));
1201                        if (width < 1) width = 1920;
1202
1203                        int height = message.getFileParams().height;
1204                        if (height < 1 && thumb.getAttribute("height") != null) height = Integer.parseInt(thumb.getAttribute("height"));
1205                        if (height < 1) height = 1080;
1206                        Rect r = rectForSize(width, height, size);
1207
1208                        Bitmap blurhash = BlurHashDecoder.INSTANCE.decode(parts[1], r.width(), r.height(), 1.0f, false);
1209                        if (blurhash != null) {
1210                            cached = new BitmapDrawable(blurhash);
1211                            if (parts[1] != null && cached != null) cache.put(parts[1], cached);
1212                            return cached;
1213                        }
1214                    } else if (parts[0].equals("image/thumbhash")) {
1215                        ThumbHash.Image image;
1216                        try {
1217                            image = ThumbHash.thumbHashToRGBA(data);
1218                        } catch (final Exception e) {
1219                            continue;
1220                        }
1221                        int[] pixels = new int[image.width * image.height];
1222                        for (int i = 0; i < pixels.length; i++) {
1223                            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);
1224                        }
1225                        cached = new BitmapDrawable(Bitmap.createBitmap(pixels, image.width, image.height, Bitmap.Config.ARGB_8888));
1226                        if (parts[1] != null && cached != null) cache.put(parts[1], cached);
1227                        return cached;
1228                    }
1229                }
1230            }
1231         }
1232
1233        return null;
1234    }
1235
1236    public Drawable getThumbnail(Message message, Resources res, int size, boolean cacheOnly) throws IOException {
1237        final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
1238        DownloadableFile file = getFile(message);
1239        Drawable thumbnail = cache.get(file.getAbsolutePath());
1240        if (thumbnail != null) return thumbnail;
1241
1242        if ((thumbnail == null) && (!cacheOnly)) {
1243            synchronized (THUMBNAIL_LOCK) {
1244                final var thumbs = message.getFileParams() != null ? message.getFileParams().getThumbnails() : null;
1245                if (thumbs != null && !thumbs.isEmpty()) {
1246                    for (final var thumb : thumbs) {
1247                        final var uriS = thumb.getAttribute("uri");
1248                        if (uriS == null) continue;
1249                        Uri uri = Uri.parse(uriS);
1250                        if (uri.getScheme().equals("data")) {
1251                            if (android.os.Build.VERSION.SDK_INT < 28) continue;
1252                            String[] parts = uri.getSchemeSpecificPart().split(",", 2);
1253
1254                            byte[] data;
1255                            if (Arrays.asList(parts[0].split(";")).contains("base64")) {
1256                                String[] parts2 = parts[0].split(";", 2);
1257                                parts[0] = parts2[0];
1258                                data = Base64.decode(parts[1], 0);
1259                            } else {
1260                                data = parts[1].getBytes("UTF-8");
1261                            }
1262
1263                            if (parts[0].equals("image/blurhash")) continue; // blurhash only for fallback
1264                            if (parts[0].equals("image/thumbhash")) continue; // thumbhash only for fallback
1265
1266                            if (android.os.Build.VERSION.SDK_INT >= 28) {
1267                                ImageDecoder.Source source = ImageDecoder.createSource(ByteBuffer.wrap(data));
1268                                thumbnail = ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1269                                    int w = info.getSize().getWidth();
1270                                    int h = info.getSize().getHeight();
1271                                    Rect r = rectForSize(w, h, size);
1272                                    decoder.setTargetSize(r.width(), r.height());
1273                                });
1274                            }
1275
1276                            if (thumbnail != null && file.getAbsolutePath() != null) {
1277                                cache.put(file.getAbsolutePath(), thumbnail);
1278                                return thumbnail;
1279                            }
1280                        } else if (uri.getScheme().equals("cid")) {
1281                            Cid cid = BobTransfer.cid(uri);
1282                            if (cid == null) continue;
1283                            DownloadableFile f = mXmppConnectionService.getFileForCid(cid);
1284                            if (f != null && f.canRead()) {
1285                                return getThumbnail(f, res, size, cacheOnly);
1286                            }
1287                        }
1288                    }
1289                }
1290            }
1291        }
1292
1293        return getThumbnail(file, res, size, cacheOnly);
1294    }
1295
1296    public Drawable getThumbnail(DownloadableFile file, Resources res, int size, boolean cacheOnly) throws IOException {
1297        return getThumbnail(file, res, size, cacheOnly, file.getAbsolutePath());
1298    }
1299
1300    public Drawable getThumbnail(DownloadableFile file, Resources res, int size, boolean cacheOnly, String cacheKey) throws IOException {
1301        final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
1302        Drawable thumbnail = cache.get(cacheKey);
1303        if ((thumbnail == null) && (!cacheOnly) && file.exists()) {
1304            synchronized (THUMBNAIL_LOCK) {
1305                thumbnail = cache.get(cacheKey);
1306                if (thumbnail != null) {
1307                    return thumbnail;
1308                }
1309                final String mime = file.getMimeType();
1310                if ("image/svg+xml".equals(mime)) {
1311                    thumbnail = getSVG(file, size);
1312                } else if ("application/pdf".equals(mime)) {
1313                    thumbnail = new BitmapDrawable(res, getPdfDocumentPreview(file, size));
1314                } else if (mime.startsWith("video/")) {
1315                    thumbnail = new BitmapDrawable(res, getVideoPreview(file, size));
1316                } else if (mime.startsWith("audio/")) {
1317                    thumbnail = res.getDrawable(R.drawable.audio_file_24dp);
1318                } else {
1319                    thumbnail = getImagePreview(file, res, size, mime);
1320                    if (thumbnail == null) {
1321                        throw new FileNotFoundException();
1322                    }
1323                }
1324                if (cacheKey != null && thumbnail != null) cache.put(cacheKey, thumbnail);
1325            }
1326        }
1327        return thumbnail;
1328    }
1329
1330    public Bitmap getThumbnailBitmap(Message message, Resources res, int size) throws IOException {
1331          final Drawable drawable = getThumbnail(message, res, size, false);
1332          if (drawable == null) return null;
1333          return drawDrawable(drawable);
1334    }
1335
1336    public Bitmap getThumbnailBitmap(DownloadableFile file, Resources res, int size, String cacheKey) throws IOException {
1337          final Drawable drawable = getThumbnail(file, res, size, false, cacheKey);
1338          if (drawable == null) return null;
1339          return drawDrawable(drawable);
1340    }
1341
1342    public static Rect rectForSize(int w, int h, int size) {
1343        int scalledW;
1344        int scalledH;
1345        if (w <= h) {
1346            scalledW = Math.max((int) (w / ((double) h / size)), 1);
1347            scalledH = size;
1348        } else {
1349            scalledW = size;
1350            scalledH = Math.max((int) (h / ((double) w / size)), 1);
1351        }
1352
1353        if (scalledW > w || scalledH > h) return new Rect(0, 0, w, h);
1354
1355        return new Rect(0, 0, scalledW, scalledH);
1356    }
1357
1358    private Drawable getImagePreview(File file, Resources res, int size, final String mime) throws IOException {
1359        if (android.os.Build.VERSION.SDK_INT >= 28) {
1360            ImageDecoder.Source source = ImageDecoder.createSource(file);
1361            return ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1362                int w = info.getSize().getWidth();
1363                int h = info.getSize().getHeight();
1364                Rect r = rectForSize(w, h, size);
1365                decoder.setTargetSize(r.width(), r.height());
1366            });
1367        } else {
1368            BitmapFactory.Options options = new BitmapFactory.Options();
1369            options.inSampleSize = calcSampleSize(file, size);
1370            Bitmap bitmap = null;
1371            try {
1372                bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1373            } catch (OutOfMemoryError e) {
1374                options.inSampleSize *= 2;
1375                bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1376            }
1377            if (bitmap == null) return null;
1378
1379            bitmap = resize(bitmap, size);
1380            bitmap = rotate(bitmap, getRotation(file));
1381            if (mime.equals("image/gif")) {
1382                Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
1383                drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
1384                bitmap.recycle();
1385                bitmap = withGifOverlay;
1386            }
1387            return new BitmapDrawable(res, bitmap);
1388        }
1389    }
1390
1391    public static Bitmap drawDrawable(Drawable drawable) {
1392        if (drawable == null) return null;
1393
1394        Bitmap bitmap = null;
1395
1396        if (drawable instanceof BitmapDrawable) {
1397            bitmap = ((BitmapDrawable) drawable).getBitmap();
1398            if (bitmap != null) return bitmap;
1399        }
1400
1401        Rect bounds = drawable.getBounds();
1402        int width = drawable.getIntrinsicWidth();
1403        if (width < 1) width = bounds == null || bounds.right < 1 ? 256 : bounds.right;
1404        int height = drawable.getIntrinsicHeight();
1405        if (height < 1) height = bounds == null || bounds.bottom < 1 ? 256 : bounds.bottom;
1406
1407        if (width < 1) {
1408            Log.w(Config.LOGTAG, "Drawable with no width: " + drawable);
1409            width = 48;
1410        }
1411        if (height < 1) {
1412            Log.w(Config.LOGTAG, "Drawable with no height: " + drawable);
1413            height = 48;
1414        }
1415
1416        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1417        Canvas canvas = new Canvas(bitmap);
1418        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1419        drawable.draw(canvas);
1420        return bitmap;
1421    }
1422
1423    private void drawOverlay(Bitmap bitmap, int resource, float factor) {
1424        Bitmap overlay =
1425                BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
1426        Canvas canvas = new Canvas(bitmap);
1427        float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
1428        Log.d(
1429                Config.LOGTAG,
1430                "target size overlay: "
1431                        + targetSize
1432                        + " overlay bitmap size was "
1433                        + overlay.getHeight());
1434        float left = (canvas.getWidth() - targetSize) / 2.0f;
1435        float top = (canvas.getHeight() - targetSize) / 2.0f;
1436        RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
1437        canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
1438    }
1439
1440    /** https://stackoverflow.com/a/3943023/210897 */
1441    private boolean paintOverlayBlack(final Bitmap bitmap) {
1442        final int h = bitmap.getHeight();
1443        final int w = bitmap.getWidth();
1444        int record = 0;
1445        for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
1446            for (int x = Math.round(w * IGNORE_PADDING);
1447                    x < w - Math.round(w * IGNORE_PADDING);
1448                    ++x) {
1449                int pixel = bitmap.getPixel(x, y);
1450                if ((Color.red(pixel) * 0.299
1451                                + Color.green(pixel) * 0.587
1452                                + Color.blue(pixel) * 0.114)
1453                        > 186) {
1454                    --record;
1455                } else {
1456                    ++record;
1457                }
1458            }
1459        }
1460        return record < 0;
1461    }
1462
1463    private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
1464        final int h = bitmap.getHeight();
1465        final int w = bitmap.getWidth();
1466        int white = 0;
1467        for (int y = 0; y < h; ++y) {
1468            for (int x = 0; x < w; ++x) {
1469                int pixel = bitmap.getPixel(x, y);
1470                if ((Color.red(pixel) * 0.299
1471                                + Color.green(pixel) * 0.587
1472                                + Color.blue(pixel) * 0.114)
1473                        > 186) {
1474                    white++;
1475                }
1476            }
1477        }
1478        return white > (h * w * 0.4f);
1479    }
1480
1481    private Bitmap cropCenterSquareVideo(Uri uri, int size) {
1482        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1483        Bitmap frame;
1484        try {
1485            metadataRetriever.setDataSource(mXmppConnectionService, uri);
1486            frame = metadataRetriever.getFrameAtTime(0);
1487            metadataRetriever.release();
1488            return cropCenterSquare(frame, size);
1489        } catch (Exception e) {
1490            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1491            frame.eraseColor(0xff000000);
1492            return frame;
1493        }
1494    }
1495
1496    private Bitmap getVideoPreview(final File file, final int size) {
1497        final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1498        Bitmap frame;
1499        try {
1500            metadataRetriever.setDataSource(file.getAbsolutePath());
1501            frame = metadataRetriever.getFrameAtTime(0);
1502            metadataRetriever.release();
1503            frame = resize(frame, size);
1504        } catch (IOException | RuntimeException e) {
1505            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1506            frame.eraseColor(0xff000000);
1507        }
1508        drawOverlay(
1509                frame,
1510                paintOverlayBlack(frame)
1511                        ? R.drawable.play_video_black
1512                        : R.drawable.play_video_white,
1513                0.75f);
1514        return frame;
1515    }
1516
1517    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1518    private Bitmap getPdfDocumentPreview(final File file, final int size) {
1519        try {
1520            final ParcelFileDescriptor fileDescriptor =
1521                    ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1522            final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
1523            drawOverlay(
1524                    rendered,
1525                    paintOverlayBlackPdf(rendered)
1526                            ? R.drawable.open_pdf_black
1527                            : R.drawable.open_pdf_white,
1528                    0.75f);
1529            return rendered;
1530        } catch (final IOException | SecurityException e) {
1531            Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
1532            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1533            placeholder.eraseColor(0xff000000);
1534            return placeholder;
1535        }
1536    }
1537
1538    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1539    private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
1540        try {
1541            ParcelFileDescriptor fileDescriptor =
1542                    mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
1543            final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1544            return cropCenterSquare(bitmap, size);
1545        } catch (Exception e) {
1546            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1547            placeholder.eraseColor(0xff000000);
1548            return placeholder;
1549        }
1550    }
1551
1552    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1553    private Bitmap renderPdfDocument(
1554            ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1555        final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1556        final PdfRenderer.Page page = pdfRenderer.openPage(0);
1557        final Dimensions dimensions =
1558                scalePdfDimensions(
1559                        new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1560        final Bitmap rendered =
1561                Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1562        rendered.eraseColor(0xffffffff);
1563        page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1564        page.close();
1565        pdfRenderer.close();
1566        fileDescriptor.close();
1567        return rendered;
1568    }
1569
1570    public Uri getTakePhotoUri() {
1571        final String filename =
1572                String.format("IMG_%s.%s", IMAGE_DATE_FORMAT.format(new Date()), "jpg");
1573        final File directory;
1574        if (Config.ONLY_INTERNAL_STORAGE) {
1575            directory = new File(mXmppConnectionService.getCacheDir(), "Camera");
1576        } else {
1577            directory =
1578                    new File(
1579                            Environment.getExternalStoragePublicDirectory(
1580                                    Environment.DIRECTORY_DCIM),
1581                            "Camera");
1582        }
1583        final File file = new File(directory, filename);
1584        file.getParentFile().mkdirs();
1585        return getUriForFile(mXmppConnectionService, file);
1586    }
1587
1588    public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
1589
1590        final Pair<Avatar,Boolean> uncompressAvatar = getUncompressedAvatar(image);
1591        if (uncompressAvatar != null && uncompressAvatar.first != null &&
1592                (uncompressAvatar.first.image.length() <= Config.AVATAR_CHAR_LIMIT || uncompressAvatar.second)) {
1593            return uncompressAvatar.first;
1594        }
1595        if (uncompressAvatar != null && uncompressAvatar.first != null) {
1596            Log.d(
1597                    Config.LOGTAG,
1598                    "uncompressed avatar exceeded char limit by "
1599                            + (uncompressAvatar.first.image.length() - Config.AVATAR_CHAR_LIMIT));
1600        }
1601
1602        Bitmap bm = cropCenterSquare(image, size);
1603        if (bm == null) {
1604            return null;
1605        }
1606        if (hasAlpha(bm)) {
1607            Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
1608            bm.recycle();
1609            bm = cropCenterSquare(image, 96);
1610            return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
1611        }
1612        return getPepAvatar(bm, format, 100);
1613    }
1614
1615    private Pair<Avatar,Boolean> getUncompressedAvatar(Uri uri) {
1616        try {
1617            if (android.os.Build.VERSION.SDK_INT >= 28) {
1618                ImageDecoder.Source source = ImageDecoder.createSource(mXmppConnectionService.getContentResolver(), uri);
1619                int[] size = new int[] { 0, 0 };
1620                boolean[] animated = new boolean[] { false };
1621                String[] mimeType = new String[] { null };
1622                Drawable drawable = ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1623                    mimeType[0] = info.getMimeType();
1624                    animated[0] = info.isAnimated();
1625                    size[0] = info.getSize().getWidth();
1626                    size[1] = info.getSize().getHeight();
1627                });
1628
1629                if (animated[0]) {
1630                    Avatar avatar = getPepAvatar(uri, size[0], size[1], mimeType[0]);
1631                    if (avatar != null) return new Pair(avatar, true);
1632                }
1633
1634                return new Pair(getPepAvatar(drawDrawable(drawable), Bitmap.CompressFormat.PNG, 100), false);
1635            } else {
1636                Bitmap bitmap =
1637                    BitmapFactory.decodeStream(
1638                            mXmppConnectionService.getContentResolver().openInputStream(uri));
1639                return new Pair(getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100), false);
1640            }
1641        } catch (Exception e) {
1642            try {
1643                final SVG svg = SVG.getFromInputStream(mXmppConnectionService.getContentResolver().openInputStream(uri));
1644                return new Pair(getPepAvatar(uri, (int) svg.getDocumentWidth(), (int) svg.getDocumentHeight(), "image/svg+xml"), true);
1645            } catch (Exception e2) {
1646                return null;
1647            }
1648        }
1649    }
1650
1651    private Avatar getPepAvatar(Uri uri, int width, int height, final String mimeType) throws IOException, NoSuchAlgorithmException {
1652        AssetFileDescriptor fd = mXmppConnectionService.getContentResolver().openAssetFileDescriptor(uri, "r");
1653        if (fd.getLength() > 100000) return null; // Too big to use raw file
1654
1655        ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1656        Base64OutputStream mBase64OutputStream =
1657                new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1658        MessageDigest digest = MessageDigest.getInstance("SHA-1");
1659        DigestOutputStream mDigestOutputStream =
1660                new DigestOutputStream(mBase64OutputStream, digest);
1661
1662        ByteStreams.copy(fd.createInputStream(), mDigestOutputStream);
1663        mDigestOutputStream.flush();
1664        mDigestOutputStream.close();
1665
1666        final Avatar avatar = new Avatar();
1667        avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1668        avatar.image = new String(mByteArrayOutputStream.toByteArray());
1669        avatar.type = mimeType;
1670        avatar.width = width;
1671        avatar.height = height;
1672        return avatar;
1673    }
1674
1675    private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1676        try {
1677            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1678            Base64OutputStream mBase64OutputStream =
1679                    new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1680            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1681            DigestOutputStream mDigestOutputStream =
1682                    new DigestOutputStream(mBase64OutputStream, digest);
1683            if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1684                return null;
1685            }
1686            mDigestOutputStream.flush();
1687            mDigestOutputStream.close();
1688            long chars = mByteArrayOutputStream.size();
1689            if (format != Bitmap.CompressFormat.PNG
1690                    && quality >= 50
1691                    && chars >= Config.AVATAR_CHAR_LIMIT) {
1692                int q = quality - 2;
1693                Log.d(
1694                        Config.LOGTAG,
1695                        "avatar char length was " + chars + " reducing quality to " + q);
1696                return getPepAvatar(bitmap, format, q);
1697            }
1698            Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1699            final Avatar avatar = new Avatar();
1700            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1701            avatar.image = new String(mByteArrayOutputStream.toByteArray());
1702            if (format.equals(Bitmap.CompressFormat.WEBP)) {
1703                avatar.type = "image/webp";
1704            } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1705                avatar.type = "image/jpeg";
1706            } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1707                avatar.type = "image/png";
1708            }
1709            avatar.width = bitmap.getWidth();
1710            avatar.height = bitmap.getHeight();
1711            return avatar;
1712        } catch (OutOfMemoryError e) {
1713            Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1714            return null;
1715        } catch (Exception e) {
1716            return null;
1717        }
1718    }
1719
1720    public Avatar getStoredPepAvatar(String hash) {
1721        if (hash == null) {
1722            return null;
1723        }
1724        Avatar avatar = new Avatar();
1725        final File file = getAvatarFile(hash);
1726        FileInputStream is = null;
1727        try {
1728            avatar.size = file.length();
1729            BitmapFactory.Options options = new BitmapFactory.Options();
1730            options.inJustDecodeBounds = true;
1731            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1732            is = new FileInputStream(file);
1733            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1734            Base64OutputStream mBase64OutputStream =
1735                    new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1736            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1737            DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1738            byte[] buffer = new byte[4096];
1739            int length;
1740            while ((length = is.read(buffer)) > 0) {
1741                os.write(buffer, 0, length);
1742            }
1743            os.flush();
1744            os.close();
1745            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1746            avatar.image = new String(mByteArrayOutputStream.toByteArray());
1747            avatar.height = options.outHeight;
1748            avatar.width = options.outWidth;
1749            avatar.type = options.outMimeType;
1750            return avatar;
1751        } catch (NoSuchAlgorithmException | IOException e) {
1752            return null;
1753        } finally {
1754            close(is);
1755        }
1756    }
1757
1758    public boolean isAvatarCached(Avatar avatar) {
1759        final File file = getAvatarFile(avatar.getFilename());
1760        return file.exists();
1761    }
1762
1763    public boolean save(final Avatar avatar) {
1764        File file;
1765        if (isAvatarCached(avatar)) {
1766            file = getAvatarFile(avatar.getFilename());
1767            avatar.size = file.length();
1768        } else {
1769            file =
1770                    new File(
1771                            mXmppConnectionService.getCacheDir().getAbsolutePath()
1772                                    + "/"
1773                                    + UUID.randomUUID().toString());
1774            if (file.getParentFile().mkdirs()) {
1775                Log.d(Config.LOGTAG, "created cache directory");
1776            }
1777            OutputStream os = null;
1778            try {
1779                if (!file.createNewFile()) {
1780                    Log.d(
1781                            Config.LOGTAG,
1782                            "unable to create temporary file " + file.getAbsolutePath());
1783                }
1784                os = new FileOutputStream(file);
1785                MessageDigest digest = MessageDigest.getInstance("SHA-1");
1786                digest.reset();
1787                DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1788                final byte[] bytes = avatar.getImageAsBytes();
1789                mDigestOutputStream.write(bytes);
1790                mDigestOutputStream.flush();
1791                mDigestOutputStream.close();
1792                String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1793                if (sha1sum.equals(avatar.sha1sum)) {
1794                    final File outputFile = getAvatarFile(avatar.getFilename());
1795                    if (outputFile.getParentFile().mkdirs()) {
1796                        Log.d(Config.LOGTAG, "created avatar directory");
1797                    }
1798                    final File avatarFile = getAvatarFile(avatar.getFilename());
1799                    if (!file.renameTo(avatarFile)) {
1800                        Log.d(
1801                                Config.LOGTAG,
1802                                "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1803                        return false;
1804                    }
1805                } else {
1806                    Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1807                    if (!file.delete()) {
1808                        Log.d(Config.LOGTAG, "unable to delete temporary file");
1809                    }
1810                    return false;
1811                }
1812                avatar.size = bytes.length;
1813            } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1814                return false;
1815            } finally {
1816                close(os);
1817            }
1818        }
1819        return true;
1820    }
1821
1822    public void deleteHistoricAvatarPath() {
1823        delete(getHistoricAvatarPath());
1824    }
1825
1826    private void delete(final File file) {
1827        if (file.isDirectory()) {
1828            final File[] files = file.listFiles();
1829            if (files != null) {
1830                for (final File f : files) {
1831                    delete(f);
1832                }
1833            }
1834        }
1835        if (file.delete()) {
1836            Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1837        }
1838    }
1839
1840    private File getHistoricAvatarPath() {
1841        return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1842    }
1843
1844    public File getAvatarFile(String avatar) {
1845        final var f = new File(mXmppConnectionService.getCacheDir(), "/avatars/" + avatar);
1846        if (Build.VERSION.SDK_INT < 26) return f; // Doesn't support file.toPath
1847        try {
1848            if (f.exists()) java.nio.file.Files.setAttribute(f.toPath(), "lastAccessTime", java.nio.file.attribute.FileTime.fromMillis(System.currentTimeMillis()));
1849        } catch (final IOException e) {
1850            Log.w(Config.LOGTAG, "unable to set lastAccessTime for " + f);
1851        }
1852        return f;
1853    }
1854
1855    public Uri getAvatarUri(String avatar) {
1856        return Uri.fromFile(getAvatarFile(avatar));
1857    }
1858
1859    public Drawable cropCenterSquareDrawable(Uri image, int size) {
1860        if (android.os.Build.VERSION.SDK_INT >= 28) {
1861            try {
1862                ImageDecoder.Source source = ImageDecoder.createSource(mXmppConnectionService.getContentResolver(), image);
1863                return ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1864                    int w = info.getSize().getWidth();
1865                    int h = info.getSize().getHeight();
1866                    Rect r = rectForSize(w, h, size);
1867                    decoder.setTargetSize(r.width(), r.height());
1868
1869                    int newSize = Math.min(r.width(), r.height());
1870                    int left = (r.width() - newSize) / 2;
1871                    int top = (r.height() - newSize) / 2;
1872                    decoder.setCrop(new Rect(left, top, left + newSize, top + newSize));
1873                });
1874            } catch (final IOException e) {
1875                return getSVGSquare(image, size);
1876            }
1877        } else {
1878            Bitmap bitmap = cropCenterSquare(image, size);
1879            return bitmap == null ? null : new BitmapDrawable(bitmap);
1880        }
1881    }
1882
1883    public Bitmap cropCenterSquare(Uri image, int size) {
1884        if (image == null) {
1885            return null;
1886        }
1887        InputStream is = null;
1888        try {
1889            BitmapFactory.Options options = new BitmapFactory.Options();
1890            options.inSampleSize = calcSampleSize(image, size);
1891            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1892            if (is == null) {
1893                return null;
1894            }
1895            Bitmap input = BitmapFactory.decodeStream(is, null, options);
1896            if (input == null) {
1897                return null;
1898            } else {
1899                input = rotate(input, getRotation(image));
1900                return cropCenterSquare(input, size);
1901            }
1902        } catch (FileNotFoundException | SecurityException e) {
1903            Log.d(Config.LOGTAG, "unable to open file " + image.toString(), e);
1904            return null;
1905        } finally {
1906            close(is);
1907        }
1908    }
1909
1910    public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1911        if (image == null) {
1912            return null;
1913        }
1914        InputStream is = null;
1915        try {
1916            BitmapFactory.Options options = new BitmapFactory.Options();
1917            options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1918            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1919            if (is == null) {
1920                return null;
1921            }
1922            Bitmap source = BitmapFactory.decodeStream(is, null, options);
1923            if (source == null) {
1924                return null;
1925            }
1926            int sourceWidth = source.getWidth();
1927            int sourceHeight = source.getHeight();
1928            float xScale = (float) newWidth / sourceWidth;
1929            float yScale = (float) newHeight / sourceHeight;
1930            float scale = Math.max(xScale, yScale);
1931            float scaledWidth = scale * sourceWidth;
1932            float scaledHeight = scale * sourceHeight;
1933            float left = (newWidth - scaledWidth) / 2;
1934            float top = (newHeight - scaledHeight) / 2;
1935
1936            RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1937            Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1938            Canvas canvas = new Canvas(dest);
1939            canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1940            if (source.isRecycled()) {
1941                source.recycle();
1942            }
1943            return dest;
1944        } catch (SecurityException e) {
1945            return null; // android 6.0 with revoked permissions for example
1946        } catch (FileNotFoundException e) {
1947            return null;
1948        } finally {
1949            close(is);
1950        }
1951    }
1952
1953    public Bitmap cropCenterSquare(Bitmap input, int size) {
1954        int w = input.getWidth();
1955        int h = input.getHeight();
1956
1957        float scale = Math.max((float) size / h, (float) size / w);
1958
1959        float outWidth = scale * w;
1960        float outHeight = scale * h;
1961        float left = (size - outWidth) / 2;
1962        float top = (size - outHeight) / 2;
1963        RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1964
1965        Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1966        Canvas canvas = new Canvas(output);
1967        canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1968        if (!input.isRecycled()) {
1969            input.recycle();
1970        }
1971        return output;
1972    }
1973
1974    private int calcSampleSize(Uri image, int size)
1975            throws FileNotFoundException, SecurityException {
1976        final BitmapFactory.Options options = new BitmapFactory.Options();
1977        options.inJustDecodeBounds = true;
1978        final InputStream inputStream =
1979                mXmppConnectionService.getContentResolver().openInputStream(image);
1980        BitmapFactory.decodeStream(inputStream, null, options);
1981        close(inputStream);
1982        return calcSampleSize(options, size);
1983    }
1984
1985    public void updateFileParams(Message message) {
1986        updateFileParams(message, null);
1987    }
1988
1989    public void updateFileParams(final Message message, final String url) {
1990        updateFileParams(message, url, true);
1991    }
1992
1993    public void updateFileParams(final Message message, String url, boolean updateCids) {
1994        final boolean encrypted =
1995                message.getEncryption() == Message.ENCRYPTION_PGP
1996                        || message.getEncryption() == Message.ENCRYPTION_DECRYPTED;
1997        final DownloadableFile file = getFile(message);
1998        final String mime = file.getMimeType();
1999        final boolean privateMessage = message.isPrivateMessage();
2000        final boolean image =
2001                message.getType() == Message.TYPE_IMAGE
2002                        || (mime != null && mime.startsWith("image/"));
2003        Message.FileParams fileParams = message.getFileParams();
2004        if (fileParams == null) fileParams = new Message.FileParams();
2005        Cid[] cids = new Cid[0];
2006        try {
2007            cids = calculateCids(new FileInputStream(file));
2008            fileParams.setCids(List.of(cids));
2009        } catch (final IOException | NoSuchAlgorithmException e) { }
2010        if (url == null) {
2011            for (Cid cid : cids) {
2012                url = mXmppConnectionService.getUrlForCid(cid);
2013                if (url != null) {
2014                    fileParams.url = url;
2015                    break;
2016                }
2017            }
2018        } else {
2019            fileParams.url = url;
2020        }
2021        if (fileParams.getName() == null) fileParams.setName(file.getName());
2022        fileParams.setMediaType(mime);
2023        if (encrypted && !file.exists()) {
2024            Log.d(Config.LOGTAG, "skipping updateFileParams because file is encrypted");
2025            final DownloadableFile encryptedFile = getFile(message, false);
2026            if (encryptedFile.canRead()) fileParams.size = encryptedFile.getSize();
2027        } else {
2028            Log.d(Config.LOGTAG, "running updateFileParams");
2029            final boolean ambiguous = MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime);
2030            final boolean video = mime != null && mime.startsWith("video/");
2031            final boolean audio = mime != null && mime.startsWith("audio/");
2032            final boolean pdf = "application/pdf".equals(mime);
2033            if (file.canRead()) fileParams.size = file.getSize();
2034            if (ambiguous) {
2035                try {
2036                    final Dimensions dimensions = getVideoDimensions(file);
2037                    if (dimensions.valid()) {
2038                        Log.d(Config.LOGTAG, "ambiguous file " + mime + " is video");
2039                        fileParams.width = dimensions.width;
2040                        fileParams.height = dimensions.height;
2041                    } else {
2042                        Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
2043                        fileParams.runtime = getMediaRuntime(file);
2044                    }
2045                } catch (final IOException | NotAVideoFile e) {
2046                    Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
2047                    fileParams.runtime = getMediaRuntime(file);
2048                }
2049            } else if (image || video || pdf) {
2050                try {
2051                    final Dimensions dimensions;
2052                    if (video) {
2053                        dimensions = getVideoDimensions(file);
2054                    } else if (pdf) {
2055                        dimensions = getPdfDocumentDimensions(file);
2056                    } else if ("image/svg+xml".equals(mime)) {
2057                        SVG svg = SVG.getFromInputStream(new FileInputStream(file));
2058                        dimensions = new Dimensions((int) svg.getDocumentHeight(), (int) svg.getDocumentWidth());
2059                    } else {
2060                        dimensions = getImageDimensions(file);
2061                    }
2062                    if (dimensions.valid()) {
2063                        fileParams.width = dimensions.width;
2064                        fileParams.height = dimensions.height;
2065                    }
2066                } catch (final IOException | SVGParseException | NotAVideoFile notAVideoFile) {
2067                    Log.d(
2068                            Config.LOGTAG,
2069                            "file with mime type " + file.getMimeType() + " was not a video file");
2070                    // fall threw
2071                }
2072            } else if (audio) {
2073                fileParams.runtime = getMediaRuntime(file);
2074            }
2075            if ("application/webxdc+zip".equals(mime)) {
2076                try {
2077                    final var zip = new ZipFile(file);
2078                    final ZipEntry manifestEntry = zip == null ? null : zip.getEntry("manifest.toml");
2079                    if (manifestEntry != null) {
2080                        final var manifest = Toml.parse(zip.getInputStream(manifestEntry));
2081                        if (manifest != null) {
2082                            final var name = manifest.getString("name");
2083                            if (name != null) fileParams.setName(name);
2084                        }
2085                    }
2086                } catch (final IOException e2) { }
2087            }
2088            try {
2089                Bitmap thumb = getThumbnailBitmap(file, mXmppConnectionService.getResources(), 100, file.getAbsolutePath() + " x 100");
2090                if (thumb != null) {
2091                    int[] pixels = new int[thumb.getWidth() * thumb.getHeight()];
2092                    byte[] rgba = new byte[pixels.length * 4];
2093                    try {
2094                        thumb.getPixels(pixels, 0, thumb.getWidth(), 0, 0, thumb.getWidth(), thumb.getHeight());
2095                    } catch (final IllegalStateException e) {
2096                        Bitmap softThumb = thumb.copy(Bitmap.Config.ARGB_8888, false);
2097                        softThumb.getPixels(pixels, 0, thumb.getWidth(), 0, 0, thumb.getWidth(), thumb.getHeight());
2098                        softThumb.recycle();
2099                    }
2100                    for (int i = 0; i < pixels.length; i++) {
2101                        rgba[i*4] = (byte)((pixels[i] >> 16) & 0xff);
2102                        rgba[(i*4)+1] = (byte)((pixels[i] >> 8) & 0xff);
2103                        rgba[(i*4)+2] = (byte)(pixels[i] & 0xff);
2104                        rgba[(i*4)+3] = (byte)((pixels[i] >> 24) & 0xff);
2105                    }
2106                    fileParams.addThumbnail(thumb.getWidth(), thumb.getHeight(), "image/thumbhash", "data:image/thumbhash;base64," + Base64.encodeToString(ThumbHash.rgbaToThumbHash(thumb.getWidth(), thumb.getHeight(), rgba), Base64.NO_WRAP));
2107                }
2108            } catch (final IOException e) { }
2109        }
2110        message.setFileParams(fileParams);
2111        message.setDeleted(false);
2112        message.setType(
2113                privateMessage
2114                        ? Message.TYPE_PRIVATE_FILE
2115                        : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
2116
2117        if (updateCids) {
2118            try {
2119                for (int i = 0; i < cids.length; i++) {
2120                    mXmppConnectionService.saveCid(cids[i], file);
2121                }
2122            } catch (XmppConnectionService.BlockedMediaException e) { }
2123        }
2124    }
2125
2126    private int getMediaRuntime(final File file) {
2127        try {
2128            final MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
2129            mediaMetadataRetriever.setDataSource(file.toString());
2130            final String value =
2131                    mediaMetadataRetriever.extractMetadata(
2132                            MediaMetadataRetriever.METADATA_KEY_DURATION);
2133            if (Strings.isNullOrEmpty(value)) {
2134                return 0;
2135            }
2136            return Integer.parseInt(value);
2137        } catch (final Exception e) {
2138            return 0;
2139        }
2140    }
2141
2142    private Dimensions getImageDimensions(File file) {
2143        final BitmapFactory.Options options = new BitmapFactory.Options();
2144        options.inJustDecodeBounds = true;
2145        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
2146        final int rotation = getRotation(file);
2147        final boolean rotated = rotation == 90 || rotation == 270;
2148        final int imageHeight = rotated ? options.outWidth : options.outHeight;
2149        final int imageWidth = rotated ? options.outHeight : options.outWidth;
2150        return new Dimensions(imageHeight, imageWidth);
2151    }
2152
2153    private Dimensions getVideoDimensions(final File file) throws NotAVideoFile, IOException {
2154        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
2155        try {
2156            metadataRetriever.setDataSource(file.getAbsolutePath());
2157        } catch (RuntimeException e) {
2158            throw new NotAVideoFile(e);
2159        }
2160        return getVideoDimensions(metadataRetriever);
2161    }
2162
2163    private Dimensions getPdfDocumentDimensions(final File file) {
2164        final ParcelFileDescriptor fileDescriptor;
2165        try {
2166            fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
2167            if (fileDescriptor == null) {
2168                return new Dimensions(0, 0);
2169            }
2170        } catch (final FileNotFoundException e) {
2171            return new Dimensions(0, 0);
2172        }
2173        try {
2174            final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
2175            final PdfRenderer.Page page = pdfRenderer.openPage(0);
2176            final int height = page.getHeight();
2177            final int width = page.getWidth();
2178            page.close();
2179            pdfRenderer.close();
2180            return scalePdfDimensions(new Dimensions(height, width));
2181        } catch (final IOException | SecurityException e) {
2182            Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
2183            return new Dimensions(0, 0);
2184        }
2185    }
2186
2187    private Dimensions scalePdfDimensions(Dimensions in) {
2188        final DisplayMetrics displayMetrics =
2189                mXmppConnectionService.getResources().getDisplayMetrics();
2190        final int target = (int) (displayMetrics.density * 288);
2191        return scalePdfDimensions(in, target, true);
2192    }
2193
2194    private static Dimensions scalePdfDimensions(
2195            final Dimensions in, final int target, final boolean fit) {
2196        final int w, h;
2197        if (fit == (in.width <= in.height)) {
2198            w = Math.max((int) (in.width / ((double) in.height / target)), 1);
2199            h = target;
2200        } else {
2201            w = target;
2202            h = Math.max((int) (in.height / ((double) in.width / target)), 1);
2203        }
2204        return new Dimensions(h, w);
2205    }
2206
2207    public Drawable getAvatar(String avatar, int size) {
2208        if (avatar == null) {
2209            return null;
2210        }
2211
2212        if (android.os.Build.VERSION.SDK_INT >= 28) {
2213            try {
2214                ImageDecoder.Source source = ImageDecoder.createSource(getAvatarFile(avatar));
2215                return ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
2216                    int w = info.getSize().getWidth();
2217                    int h = info.getSize().getHeight();
2218                    Rect r = rectForSize(w, h, size);
2219                    decoder.setTargetSize(r.width(), r.height());
2220
2221                    int newSize = Math.min(r.width(), r.height());
2222                    int left = (r.width() - newSize) / 2;
2223                    int top = (r.height() - newSize) / 2;
2224                    decoder.setCrop(new Rect(left, top, left + newSize, top + newSize));
2225                });
2226            } catch (final IOException e) {
2227                return getSVGSquare(getAvatarUri(avatar), size);
2228            }
2229        } else {
2230            Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
2231            return bm == null ? null : new BitmapDrawable(bm);
2232        }
2233    }
2234
2235    public Drawable getSVGSquare(Uri uri, int size) {
2236        try {
2237            SVG svg = SVG.getFromInputStream(mXmppConnectionService.getContentResolver().openInputStream(uri));
2238            svg.setDocumentPreserveAspectRatio(com.caverock.androidsvg.PreserveAspectRatio.FULLSCREEN);
2239
2240            float w = svg.getDocumentWidth();
2241            float h = svg.getDocumentHeight();
2242            float scale = Math.max((float) size / h, (float) size / w);
2243            float outWidth = scale * w;
2244            float outHeight = scale * h;
2245            float left = (size - outWidth) / 2;
2246            float top = (size - outHeight) / 2;
2247            RectF target = new RectF(left, top, left + outWidth, top + outHeight);
2248            if (svg.getDocumentViewBox() == null) svg.setDocumentViewBox(0, 0, w, h);
2249            svg.setDocumentWidth("100%");
2250            svg.setDocumentHeight("100%");
2251
2252            Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
2253            Canvas canvas = new Canvas(output);
2254            svg.renderToCanvas(canvas, target);
2255
2256            return new SVGDrawable(output);
2257        } catch (final IOException | SVGParseException | IllegalArgumentException e) {
2258            Log.w(Config.LOGTAG, "Could not parse SVG: " + e);
2259            return null;
2260        }
2261    }
2262
2263    public Drawable getSVG(File file, int size) {
2264        try {
2265            SVG svg = SVG.getFromInputStream(new FileInputStream(file));
2266            return drawSVG(svg, size);
2267        } catch (final IOException | SVGParseException | IllegalArgumentException e) {
2268            Log.w(Config.LOGTAG, "Could not parse SVG: " + e);
2269            return null;
2270        }
2271    }
2272
2273    public Drawable drawSVG(SVG svg, int size) {
2274        try {
2275            svg.setDocumentPreserveAspectRatio(com.caverock.androidsvg.PreserveAspectRatio.LETTERBOX);
2276
2277            float w = svg.getDocumentWidth();
2278            float h = svg.getDocumentHeight();
2279            Rect r = rectForSize(w < 1 ? size : (int) w, h < 1 ? size : (int) h, size);
2280            if (svg.getDocumentViewBox() == null) svg.setDocumentViewBox(0, 0, w, h);
2281            svg.setDocumentWidth("100%");
2282            svg.setDocumentHeight("100%");
2283
2284            Bitmap output = Bitmap.createBitmap(r.width(), r.height(), Bitmap.Config.ARGB_8888);
2285            Canvas canvas = new Canvas(output);
2286            svg.renderToCanvas(canvas);
2287
2288            return new SVGDrawable(output);
2289        } catch (final SVGParseException e) {
2290            Log.w(Config.LOGTAG, "Could not parse SVG: " + e);
2291            return null;
2292        }
2293    }
2294
2295    private static class Dimensions {
2296        public final int width;
2297        public final int height;
2298
2299        Dimensions(int height, int width) {
2300            this.width = width;
2301            this.height = height;
2302        }
2303
2304        public int getMin() {
2305            return Math.min(width, height);
2306        }
2307
2308        public boolean valid() {
2309            return width > 0 && height > 0;
2310        }
2311    }
2312
2313    private static class NotAVideoFile extends Exception {
2314        public NotAVideoFile(Throwable t) {
2315            super(t);
2316        }
2317
2318        public NotAVideoFile() {
2319            super();
2320        }
2321    }
2322
2323    public static class ImageCompressionException extends Exception {
2324
2325        ImageCompressionException(String message) {
2326            super(message);
2327        }
2328    }
2329
2330    public static class FileCopyException extends Exception {
2331        private final int resId;
2332
2333        private FileCopyException(@StringRes int resId) {
2334            this.resId = resId;
2335        }
2336
2337        public @StringRes int getResId() {
2338            return resId;
2339        }
2340    }
2341
2342    public static class SVGDrawable extends BitmapDrawable {
2343        public SVGDrawable(Bitmap bm) { super(bm); }
2344    }
2345}