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