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(mXmppConnectionService, 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 static int getRotation(final Context context, final Uri image) {
 934        try (final InputStream is = context.getContentResolver().openInputStream(image)) {
 935            return is == null ? 0 : getRotation(is);
 936        } catch (final Exception e) {
 937            return 0;
 938        }
 939    }
 940
 941    private static int getRotation(final InputStream inputStream) throws IOException {
 942        final ExifInterface exif = new ExifInterface(inputStream);
 943        final int orientation =
 944                exif.getAttributeInt(
 945                        ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
 946        switch (orientation) {
 947            case ExifInterface.ORIENTATION_ROTATE_180:
 948                return 180;
 949            case ExifInterface.ORIENTATION_ROTATE_90:
 950                return 90;
 951            case ExifInterface.ORIENTATION_ROTATE_270:
 952                return 270;
 953            default:
 954                return 0;
 955        }
 956    }
 957
 958    public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
 959        final String uuid = message.getUuid();
 960        final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
 961        Bitmap thumbnail = cache.get(uuid);
 962        if ((thumbnail == null) && (!cacheOnly)) {
 963            synchronized (THUMBNAIL_LOCK) {
 964                thumbnail = cache.get(uuid);
 965                if (thumbnail != null) {
 966                    return thumbnail;
 967                }
 968                DownloadableFile file = getFile(message);
 969                final String mime = file.getMimeType();
 970                if ("application/pdf".equals(mime)) {
 971                    thumbnail = getPdfDocumentPreview(file, size);
 972                } else if (mime.startsWith("video/")) {
 973                    thumbnail = getVideoPreview(file, size);
 974                } else {
 975                    final Bitmap fullSize = getFullSizeImagePreview(file, size);
 976                    if (fullSize == null) {
 977                        throw new FileNotFoundException();
 978                    }
 979                    thumbnail = resize(fullSize, size);
 980                    thumbnail = rotate(thumbnail, getRotation(file));
 981                    if (mime.equals("image/gif")) {
 982                        Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
 983                        drawOverlay(
 984                                withGifOverlay,
 985                                paintOverlayBlack(withGifOverlay)
 986                                        ? R.drawable.play_gif_black
 987                                        : R.drawable.play_gif_white,
 988                                1.0f);
 989                        thumbnail.recycle();
 990                        thumbnail = withGifOverlay;
 991                    }
 992                }
 993                cache.put(uuid, thumbnail);
 994            }
 995        }
 996        return thumbnail;
 997    }
 998
 999    private Bitmap getFullSizeImagePreview(File file, int size) {
1000        BitmapFactory.Options options = new BitmapFactory.Options();
1001        options.inSampleSize = calcSampleSize(file, size);
1002        try {
1003            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1004        } catch (OutOfMemoryError e) {
1005            options.inSampleSize *= 2;
1006            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1007        }
1008    }
1009
1010    private void drawOverlay(Bitmap bitmap, int resource, float factor) {
1011        Bitmap overlay =
1012                BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
1013        Canvas canvas = new Canvas(bitmap);
1014        float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
1015        Log.d(
1016                Config.LOGTAG,
1017                "target size overlay: "
1018                        + targetSize
1019                        + " overlay bitmap size was "
1020                        + overlay.getHeight());
1021        float left = (canvas.getWidth() - targetSize) / 2.0f;
1022        float top = (canvas.getHeight() - targetSize) / 2.0f;
1023        RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
1024        canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
1025    }
1026
1027    /** https://stackoverflow.com/a/3943023/210897 */
1028    private boolean paintOverlayBlack(final Bitmap bitmap) {
1029        final int h = bitmap.getHeight();
1030        final int w = bitmap.getWidth();
1031        int record = 0;
1032        for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
1033            for (int x = Math.round(w * IGNORE_PADDING);
1034                    x < w - Math.round(w * IGNORE_PADDING);
1035                    ++x) {
1036                int pixel = bitmap.getPixel(x, y);
1037                if ((Color.red(pixel) * 0.299
1038                                + Color.green(pixel) * 0.587
1039                                + Color.blue(pixel) * 0.114)
1040                        > 186) {
1041                    --record;
1042                } else {
1043                    ++record;
1044                }
1045            }
1046        }
1047        return record < 0;
1048    }
1049
1050    private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
1051        final int h = bitmap.getHeight();
1052        final int w = bitmap.getWidth();
1053        int white = 0;
1054        for (int y = 0; y < h; ++y) {
1055            for (int x = 0; x < w; ++x) {
1056                int pixel = bitmap.getPixel(x, y);
1057                if ((Color.red(pixel) * 0.299
1058                                + Color.green(pixel) * 0.587
1059                                + Color.blue(pixel) * 0.114)
1060                        > 186) {
1061                    white++;
1062                }
1063            }
1064        }
1065        return white > (h * w * 0.4f);
1066    }
1067
1068    private Bitmap cropCenterSquareVideo(Uri uri, int size) {
1069        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1070        Bitmap frame;
1071        try {
1072            metadataRetriever.setDataSource(mXmppConnectionService, uri);
1073            frame = metadataRetriever.getFrameAtTime(0);
1074            metadataRetriever.release();
1075            return cropCenterSquare(frame, size);
1076        } catch (Exception e) {
1077            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1078            frame.eraseColor(0xff000000);
1079            return frame;
1080        }
1081    }
1082
1083    private Bitmap getVideoPreview(final File file, final int size) {
1084        final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1085        Bitmap frame;
1086        try {
1087            metadataRetriever.setDataSource(file.getAbsolutePath());
1088            frame = metadataRetriever.getFrameAtTime(0);
1089            metadataRetriever.release();
1090            frame = resize(frame, size);
1091        } catch (IOException | RuntimeException e) {
1092            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1093            frame.eraseColor(0xff000000);
1094        }
1095        drawOverlay(
1096                frame,
1097                paintOverlayBlack(frame)
1098                        ? R.drawable.play_video_black
1099                        : R.drawable.play_video_white,
1100                0.75f);
1101        return frame;
1102    }
1103
1104    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1105    private Bitmap getPdfDocumentPreview(final File file, final int size) {
1106        try {
1107            final ParcelFileDescriptor fileDescriptor =
1108                    ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1109            final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
1110            drawOverlay(
1111                    rendered,
1112                    paintOverlayBlackPdf(rendered)
1113                            ? R.drawable.open_pdf_black
1114                            : R.drawable.open_pdf_white,
1115                    0.75f);
1116            return rendered;
1117        } catch (final IOException | SecurityException e) {
1118            Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
1119            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1120            placeholder.eraseColor(0xff000000);
1121            return placeholder;
1122        }
1123    }
1124
1125    private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
1126        try {
1127            ParcelFileDescriptor fileDescriptor =
1128                    mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
1129            final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1130            return cropCenterSquare(bitmap, size);
1131        } catch (Exception e) {
1132            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1133            placeholder.eraseColor(0xff000000);
1134            return placeholder;
1135        }
1136    }
1137
1138    private Bitmap renderPdfDocument(
1139            ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1140        final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1141        final PdfRenderer.Page page = pdfRenderer.openPage(0);
1142        final Dimensions dimensions =
1143                scalePdfDimensions(
1144                        new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1145        final Bitmap rendered =
1146                Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1147        rendered.eraseColor(0xffffffff);
1148        page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1149        page.close();
1150        pdfRenderer.close();
1151        fileDescriptor.close();
1152        return rendered;
1153    }
1154
1155    public Uri getTakePhotoUri() {
1156        final String filename =
1157                String.format("IMG_%s.%s", IMAGE_DATE_FORMAT.format(new Date()), "jpg");
1158        final File directory;
1159        if (Config.ONLY_INTERNAL_STORAGE) {
1160            directory = new File(mXmppConnectionService.getCacheDir(), "Camera");
1161        } else {
1162            directory =
1163                    new File(
1164                            Environment.getExternalStoragePublicDirectory(
1165                                    Environment.DIRECTORY_DCIM),
1166                            "Camera");
1167        }
1168        final File file = new File(directory, filename);
1169        file.getParentFile().mkdirs();
1170        return getUriForFile(mXmppConnectionService, file);
1171    }
1172
1173    public Avatar getPepAvatar(
1174            final Uri image, final int size, final Bitmap.CompressFormat format) {
1175
1176        final Avatar uncompressAvatar = getUncompressedAvatar(image);
1177        if (uncompressAvatar != null
1178                && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
1179            return uncompressAvatar;
1180        }
1181        if (uncompressAvatar != null) {
1182            Log.d(
1183                    Config.LOGTAG,
1184                    "uncompressed avatar exceeded char limit by "
1185                            + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
1186        }
1187
1188        Bitmap bm = cropCenterSquare(image, size);
1189        if (bm == null) {
1190            return null;
1191        }
1192        if (hasAlpha(bm)) {
1193            Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
1194            bm.recycle();
1195            bm = cropCenterSquare(image, 96);
1196            return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
1197        }
1198        return getPepAvatar(bm, format, 100);
1199    }
1200
1201    private Avatar getUncompressedAvatar(Uri uri) {
1202        Bitmap bitmap = null;
1203        try {
1204            bitmap =
1205                    BitmapFactory.decodeStream(
1206                            mXmppConnectionService.getContentResolver().openInputStream(uri));
1207            return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
1208        } catch (Exception e) {
1209            return null;
1210        } finally {
1211            if (bitmap != null) {
1212                bitmap.recycle();
1213            }
1214        }
1215    }
1216
1217    private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1218        try {
1219            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1220            Base64OutputStream mBase64OutputStream =
1221                    new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT | Base64.NO_WRAP);
1222            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1223            DigestOutputStream mDigestOutputStream =
1224                    new DigestOutputStream(mBase64OutputStream, digest);
1225            if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1226                return null;
1227            }
1228            mDigestOutputStream.flush();
1229            mDigestOutputStream.close();
1230            long chars = mByteArrayOutputStream.size();
1231            if (format != Bitmap.CompressFormat.PNG
1232                    && quality >= 50
1233                    && chars >= Config.AVATAR_CHAR_LIMIT) {
1234                int q = quality - 2;
1235                Log.d(
1236                        Config.LOGTAG,
1237                        "avatar char length was " + chars + " reducing quality to " + q);
1238                return getPepAvatar(bitmap, format, q);
1239            }
1240            Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1241            final Avatar avatar = new Avatar();
1242            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1243            avatar.image = mByteArrayOutputStream.toString();
1244            if (format.equals(Bitmap.CompressFormat.WEBP)) {
1245                avatar.type = "image/webp";
1246            } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1247                avatar.type = "image/jpeg";
1248            } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1249                avatar.type = "image/png";
1250            }
1251            avatar.width = bitmap.getWidth();
1252            avatar.height = bitmap.getHeight();
1253            return avatar;
1254        } catch (OutOfMemoryError e) {
1255            Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1256            return null;
1257        } catch (Exception e) {
1258            return null;
1259        }
1260    }
1261
1262    // this was used by republishAvatarIfNeeded()
1263    public Avatar getStoredPepAvatar(String hash) {
1264        if (hash == null) {
1265            return null;
1266        }
1267        Avatar avatar = new Avatar();
1268        final File file = getAvatarFile(hash);
1269        FileInputStream is = null;
1270        try {
1271            avatar.size = file.length();
1272            BitmapFactory.Options options = new BitmapFactory.Options();
1273            options.inJustDecodeBounds = true;
1274            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1275            is = new FileInputStream(file);
1276            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1277            Base64OutputStream mBase64OutputStream =
1278                    new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1279            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1280            DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1281            byte[] buffer = new byte[4096];
1282            int length;
1283            while ((length = is.read(buffer)) > 0) {
1284                os.write(buffer, 0, length);
1285            }
1286            os.flush();
1287            os.close();
1288            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1289            avatar.image = mByteArrayOutputStream.toString();
1290            avatar.height = options.outHeight;
1291            avatar.width = options.outWidth;
1292            avatar.type = options.outMimeType;
1293            return avatar;
1294        } catch (NoSuchAlgorithmException | IOException e) {
1295            return null;
1296        } finally {
1297            close(is);
1298        }
1299    }
1300
1301    public boolean isAvatarCached(Avatar avatar) {
1302        final File file = getAvatarFile(avatar.getFilename());
1303        return file.exists();
1304    }
1305
1306    public boolean save(final Avatar avatar) {
1307        File file;
1308        if (isAvatarCached(avatar)) {
1309            file = getAvatarFile(avatar.getFilename());
1310            avatar.size = file.length();
1311        } else {
1312            file =
1313                    new File(
1314                            mXmppConnectionService.getCacheDir().getAbsolutePath()
1315                                    + "/"
1316                                    + UUID.randomUUID().toString());
1317            if (file.getParentFile().mkdirs()) {
1318                Log.d(Config.LOGTAG, "created cache directory");
1319            }
1320            OutputStream os = null;
1321            try {
1322                if (!file.createNewFile()) {
1323                    Log.d(
1324                            Config.LOGTAG,
1325                            "unable to create temporary file " + file.getAbsolutePath());
1326                }
1327                os = new FileOutputStream(file);
1328                MessageDigest digest = MessageDigest.getInstance("SHA-1");
1329                digest.reset();
1330                DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1331                final byte[] bytes = avatar.getImageAsBytes();
1332                mDigestOutputStream.write(bytes);
1333                mDigestOutputStream.flush();
1334                mDigestOutputStream.close();
1335                String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1336                if (sha1sum.equals(avatar.sha1sum)) {
1337                    final File outputFile = getAvatarFile(avatar.getFilename());
1338                    if (outputFile.getParentFile().mkdirs()) {
1339                        Log.d(Config.LOGTAG, "created avatar directory");
1340                    }
1341                    final File avatarFile = getAvatarFile(avatar.getFilename());
1342                    if (!file.renameTo(avatarFile)) {
1343                        Log.d(
1344                                Config.LOGTAG,
1345                                "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1346                        return false;
1347                    }
1348                } else {
1349                    Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1350                    if (!file.delete()) {
1351                        Log.d(Config.LOGTAG, "unable to delete temporary file");
1352                    }
1353                    return false;
1354                }
1355                avatar.size = bytes.length;
1356            } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1357                return false;
1358            } finally {
1359                close(os);
1360            }
1361        }
1362        return true;
1363    }
1364
1365    public void deleteHistoricAvatarPath() {
1366        delete(getHistoricAvatarPath());
1367    }
1368
1369    private void delete(final File file) {
1370        if (file.isDirectory()) {
1371            final File[] files = file.listFiles();
1372            if (files != null) {
1373                for (final File f : files) {
1374                    delete(f);
1375                }
1376            }
1377        }
1378        if (file.delete()) {
1379            Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1380        }
1381    }
1382
1383    private File getHistoricAvatarPath() {
1384        return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1385    }
1386
1387    public File getAvatarFile(final String avatar) {
1388        return getAvatarFile(mXmppConnectionService, avatar);
1389    }
1390
1391    public static File getAvatarFile(Context context, final String avatar) {
1392        return new File(context.getCacheDir(), "/avatars/" + avatar);
1393    }
1394
1395    public Uri getAvatarUri(String avatar) {
1396        return Uri.fromFile(getAvatarFile(avatar));
1397    }
1398
1399    public Bitmap cropCenterSquare(final Uri image, final int size) {
1400        return cropCenterSquare(mXmppConnectionService, image, size);
1401    }
1402
1403    public static Bitmap cropCenterSquare(final Context context, final Uri image, final int size) {
1404        if (image == null) {
1405            return null;
1406        }
1407        final BitmapFactory.Options options = new BitmapFactory.Options();
1408        try {
1409            options.inSampleSize = calcSampleSize(context, image, size);
1410        } catch (final IOException | SecurityException e) {
1411            Log.d(Config.LOGTAG, "unable to calculate sample size for " + image, e);
1412            return null;
1413        }
1414        try (final InputStream is = context.getContentResolver().openInputStream(image)) {
1415            if (is == null) {
1416                return null;
1417            }
1418            final var originalBitmap = BitmapFactory.decodeStream(is, null, options);
1419            if (originalBitmap == null) {
1420                return null;
1421            } else {
1422                final var bitmap = rotate(originalBitmap, getRotation(context, image));
1423                return cropCenterSquare(bitmap, size);
1424            }
1425        } catch (final SecurityException | IOException e) {
1426            Log.d(Config.LOGTAG, "unable to open file " + image, e);
1427            return null;
1428        }
1429    }
1430
1431    public Bitmap cropCenter(final Uri image, final int newHeight, final int newWidth) {
1432        if (image == null) {
1433            return null;
1434        }
1435        InputStream is = null;
1436        try {
1437            BitmapFactory.Options options = new BitmapFactory.Options();
1438            options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1439            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1440            if (is == null) {
1441                return null;
1442            }
1443            Bitmap source = BitmapFactory.decodeStream(is, null, options);
1444            if (source == null) {
1445                return null;
1446            }
1447            int sourceWidth = source.getWidth();
1448            int sourceHeight = source.getHeight();
1449            float xScale = (float) newWidth / sourceWidth;
1450            float yScale = (float) newHeight / sourceHeight;
1451            float scale = Math.max(xScale, yScale);
1452            float scaledWidth = scale * sourceWidth;
1453            float scaledHeight = scale * sourceHeight;
1454            float left = (newWidth - scaledWidth) / 2;
1455            float top = (newHeight - scaledHeight) / 2;
1456
1457            RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1458            Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1459            Canvas canvas = new Canvas(dest);
1460            canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1461            if (source.isRecycled()) {
1462                source.recycle();
1463            }
1464            return dest;
1465        } catch (SecurityException e) {
1466            return null; // android 6.0 with revoked permissions for example
1467        } catch (IOException e) {
1468            return null;
1469        } finally {
1470            close(is);
1471        }
1472    }
1473
1474    public static Bitmap cropCenterSquare(Bitmap input, int size) {
1475        int w = input.getWidth();
1476        int h = input.getHeight();
1477
1478        float scale = Math.max((float) size / h, (float) size / w);
1479
1480        float outWidth = scale * w;
1481        float outHeight = scale * h;
1482        float left = (size - outWidth) / 2;
1483        float top = (size - outHeight) / 2;
1484        RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1485
1486        Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1487        Canvas canvas = new Canvas(output);
1488        canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1489        if (!input.isRecycled()) {
1490            input.recycle();
1491        }
1492        return output;
1493    }
1494
1495    private int calcSampleSize(final Uri image, int size) throws IOException, SecurityException {
1496        return calcSampleSize(mXmppConnectionService, image, size);
1497    }
1498
1499    private static int calcSampleSize(final Context context, final Uri image, int size)
1500            throws IOException, SecurityException {
1501        final BitmapFactory.Options options = new BitmapFactory.Options();
1502        options.inJustDecodeBounds = true;
1503        try (final InputStream inputStream = context.getContentResolver().openInputStream(image)) {
1504            BitmapFactory.decodeStream(inputStream, null, options);
1505            return calcSampleSize(options, size);
1506        }
1507    }
1508
1509    public void updateFileParams(final Message message) {
1510        updateFileParams(message, null);
1511    }
1512
1513    public void updateFileParams(final Message message, final String url) {
1514        final boolean encrypted =
1515                message.getEncryption() == Message.ENCRYPTION_PGP
1516                        || message.getEncryption() == Message.ENCRYPTION_DECRYPTED;
1517        final DownloadableFile file = getFile(message);
1518        final String mime = file.getMimeType();
1519        final boolean image =
1520                message.getType() == Message.TYPE_IMAGE
1521                        || (mime != null && mime.startsWith("image/"));
1522        final boolean privateMessage = message.isPrivateMessage();
1523        final StringBuilder body = new StringBuilder();
1524        if (url != null) {
1525            body.append(url);
1526        }
1527        if (encrypted && !file.exists()) {
1528            Log.d(Config.LOGTAG, "skipping updateFileParams because file is encrypted");
1529            final DownloadableFile encryptedFile = getFile(message, false);
1530            body.append('|').append(encryptedFile.getSize());
1531        } else {
1532            Log.d(Config.LOGTAG, "running updateFileParams");
1533            final boolean ambiguous = MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime);
1534            final boolean video = mime != null && mime.startsWith("video/");
1535            final boolean audio = mime != null && mime.startsWith("audio/");
1536            final boolean pdf = "application/pdf".equals(mime);
1537            body.append('|').append(file.getSize());
1538            if (ambiguous) {
1539                try {
1540                    final Dimensions dimensions = getVideoDimensions(file);
1541                    if (dimensions.valid()) {
1542                        Log.d(Config.LOGTAG, "ambiguous file " + mime + " is video");
1543                        body.append('|')
1544                                .append(dimensions.width)
1545                                .append('|')
1546                                .append(dimensions.height);
1547                    } else {
1548                        Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1549                        body.append("|0|0|").append(getMediaRuntime(file));
1550                    }
1551                } catch (final IOException | NotAVideoFile e) {
1552                    Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1553                    body.append("|0|0|").append(getMediaRuntime(file));
1554                }
1555            } else if (image || video || pdf) {
1556                try {
1557                    final Dimensions dimensions;
1558                    if (video) {
1559                        dimensions = getVideoDimensions(file);
1560                    } else if (pdf) {
1561                        dimensions = getPdfDocumentDimensions(file);
1562                    } else {
1563                        dimensions = getImageDimensions(file);
1564                    }
1565                    if (dimensions.valid()) {
1566                        body.append('|')
1567                                .append(dimensions.width)
1568                                .append('|')
1569                                .append(dimensions.height);
1570                    }
1571                } catch (final IOException | NotAVideoFile notAVideoFile) {
1572                    Log.d(
1573                            Config.LOGTAG,
1574                            "file with mime type " + file.getMimeType() + " was not a video file");
1575                    // fall threw
1576                }
1577            } else if (audio) {
1578                body.append("|0|0|").append(getMediaRuntime(file));
1579            }
1580        }
1581        message.setBody(body.toString());
1582        message.setDeleted(false);
1583        message.setType(
1584                privateMessage
1585                        ? Message.TYPE_PRIVATE_FILE
1586                        : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
1587    }
1588
1589    private int getMediaRuntime(final File file) {
1590        try {
1591            final MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1592            mediaMetadataRetriever.setDataSource(file.toString());
1593            final String value =
1594                    mediaMetadataRetriever.extractMetadata(
1595                            MediaMetadataRetriever.METADATA_KEY_DURATION);
1596            if (Strings.isNullOrEmpty(value)) {
1597                return 0;
1598            }
1599            return Integer.parseInt(value);
1600        } catch (final Exception e) {
1601            return 0;
1602        }
1603    }
1604
1605    private Dimensions getImageDimensions(File file) {
1606        final BitmapFactory.Options options = new BitmapFactory.Options();
1607        options.inJustDecodeBounds = true;
1608        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1609        final int rotation = getRotation(file);
1610        final boolean rotated = rotation == 90 || rotation == 270;
1611        final int imageHeight = rotated ? options.outWidth : options.outHeight;
1612        final int imageWidth = rotated ? options.outHeight : options.outWidth;
1613        return new Dimensions(imageHeight, imageWidth);
1614    }
1615
1616    private Dimensions getVideoDimensions(final File file) throws NotAVideoFile, IOException {
1617        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1618        try {
1619            metadataRetriever.setDataSource(file.getAbsolutePath());
1620        } catch (RuntimeException e) {
1621            throw new NotAVideoFile(e);
1622        }
1623        return getVideoDimensions(metadataRetriever);
1624    }
1625
1626    private Dimensions getPdfDocumentDimensions(final File file) {
1627        final ParcelFileDescriptor fileDescriptor;
1628        try {
1629            fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1630            if (fileDescriptor == null) {
1631                return new Dimensions(0, 0);
1632            }
1633        } catch (final FileNotFoundException e) {
1634            return new Dimensions(0, 0);
1635        }
1636        try {
1637            final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1638            final PdfRenderer.Page page = pdfRenderer.openPage(0);
1639            final int height = page.getHeight();
1640            final int width = page.getWidth();
1641            page.close();
1642            pdfRenderer.close();
1643            return scalePdfDimensions(new Dimensions(height, width));
1644        } catch (final IOException | SecurityException e) {
1645            Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
1646            return new Dimensions(0, 0);
1647        }
1648    }
1649
1650    private Dimensions scalePdfDimensions(Dimensions in) {
1651        final DisplayMetrics displayMetrics =
1652                mXmppConnectionService.getResources().getDisplayMetrics();
1653        final int target = (int) (displayMetrics.density * 288);
1654        return scalePdfDimensions(in, target, true);
1655    }
1656
1657    private static Dimensions scalePdfDimensions(
1658            final Dimensions in, final int target, final boolean fit) {
1659        final int w, h;
1660        if (fit == (in.width <= in.height)) {
1661            w = Math.max((int) (in.width / ((double) in.height / target)), 1);
1662            h = target;
1663        } else {
1664            w = target;
1665            h = Math.max((int) (in.height / ((double) in.width / target)), 1);
1666        }
1667        return new Dimensions(h, w);
1668    }
1669
1670    public Bitmap getAvatar(String avatar, int size) {
1671        if (avatar == null) {
1672            return null;
1673        }
1674        Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1675        return bm;
1676    }
1677
1678    private static class Dimensions {
1679        public final int width;
1680        public final int height;
1681
1682        Dimensions(int height, int width) {
1683            this.width = width;
1684            this.height = height;
1685        }
1686
1687        public int getMin() {
1688            return Math.min(width, height);
1689        }
1690
1691        public boolean valid() {
1692            return width > 0 && height > 0;
1693        }
1694    }
1695
1696    private static class NotAVideoFile extends Exception {
1697        public NotAVideoFile(Throwable t) {
1698            super(t);
1699        }
1700
1701        public NotAVideoFile() {
1702            super();
1703        }
1704    }
1705
1706    public static class ImageCompressionException extends Exception {
1707
1708        ImageCompressionException(String message) {
1709            super(message);
1710        }
1711    }
1712
1713    public static class FileCopyException extends Exception {
1714        private final int resId;
1715
1716        private FileCopyException(@StringRes int resId) {
1717            this.resId = resId;
1718        }
1719
1720        public @StringRes int getResId() {
1721            return resId;
1722        }
1723    }
1724}