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