FileBackend.java

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