FileBackend.java

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