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