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