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