FileBackend.java

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