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