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