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