FileBackend.java

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