FileBackend.java

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