FileBackend.java

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