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