FileBackend.java

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