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