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