FileBackend.java

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