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