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