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;
  34import androidx.exifinterface.media.ExifInterface;
  35
  36import com.google.common.io.ByteStreams;
  37
  38import java.io.ByteArrayOutputStream;
  39import java.io.Closeable;
  40import java.io.File;
  41import java.io.FileDescriptor;
  42import java.io.FileInputStream;
  43import java.io.FileNotFoundException;
  44import java.io.FileOutputStream;
  45import java.io.IOException;
  46import java.io.InputStream;
  47import java.io.OutputStream;
  48import java.net.ServerSocket;
  49import java.net.Socket;
  50import java.security.DigestOutputStream;
  51import java.security.MessageDigest;
  52import java.security.NoSuchAlgorithmException;
  53import java.text.SimpleDateFormat;
  54import java.util.ArrayList;
  55import java.util.Date;
  56import java.util.List;
  57import java.util.Locale;
  58import java.util.UUID;
  59
  60import eu.siacs.conversations.Config;
  61import eu.siacs.conversations.R;
  62import eu.siacs.conversations.entities.DownloadableFile;
  63import eu.siacs.conversations.entities.Message;
  64import eu.siacs.conversations.services.AttachFileToConversationRunnable;
  65import eu.siacs.conversations.services.XmppConnectionService;
  66import eu.siacs.conversations.ui.RecordingActivity;
  67import eu.siacs.conversations.ui.util.Attachment;
  68import eu.siacs.conversations.utils.Compatibility;
  69import eu.siacs.conversations.utils.CryptoHelper;
  70import eu.siacs.conversations.utils.FileUtils;
  71import eu.siacs.conversations.utils.FileWriterException;
  72import eu.siacs.conversations.utils.MimeUtils;
  73import eu.siacs.conversations.xmpp.pep.Avatar;
  74
  75public class FileBackend {
  76
  77    private static final Object THUMBNAIL_LOCK = new Object();
  78
  79    private static final SimpleDateFormat IMAGE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
  80
  81    private static final String FILE_PROVIDER = ".files";
  82    private static final float IGNORE_PADDING = 0.15f;
  83    private final XmppConnectionService mXmppConnectionService;
  84
  85    public FileBackend(XmppConnectionService service) {
  86        this.mXmppConnectionService = service;
  87    }
  88
  89    private static boolean isInDirectoryThatShouldNotBeScanned(Context context, File file) {
  90        return isInDirectoryThatShouldNotBeScanned(context, file.getAbsolutePath());
  91    }
  92
  93    public static boolean isInDirectoryThatShouldNotBeScanned(Context context, String path) {
  94        for (String type : new String[]{RecordingActivity.STORAGE_DIRECTORY_TYPE_NAME, "Files"}) {
  95            if (path.startsWith(getConversationsDirectory(context, type))) {
  96                return true;
  97            }
  98        }
  99        return false;
 100    }
 101
 102    public static long getFileSize(Context context, Uri uri) {
 103        try {
 104            final Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
 105            if (cursor != null && cursor.moveToFirst()) {
 106                long size = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
 107                cursor.close();
 108                return size;
 109            } else {
 110                return -1;
 111            }
 112        } catch (Exception e) {
 113            return -1;
 114        }
 115    }
 116
 117    public static boolean allFilesUnderSize(Context context, List<Attachment> attachments, long max) {
 118        final boolean compressVideo = !AttachFileToConversationRunnable.getVideoCompression(context).equals("uncompressed");
 119        if (max <= 0) {
 120            Log.d(Config.LOGTAG, "server did not report max file size for http upload");
 121            return true; //exception to be compatible with HTTP Upload < v0.2
 122        }
 123        for (Attachment attachment : attachments) {
 124            if (attachment.getType() != Attachment.Type.FILE) {
 125                continue;
 126            }
 127            String mime = attachment.getMime();
 128            if (mime != null && mime.startsWith("video/") && compressVideo) {
 129                try {
 130                    Dimensions dimensions = FileBackend.getVideoDimensions(context, attachment.getUri());
 131                    if (dimensions.getMin() > 720) {
 132                        Log.d(Config.LOGTAG, "do not consider video file with min width larger than 720 for size check");
 133                        continue;
 134                    }
 135                } catch (NotAVideoFile notAVideoFile) {
 136                    //ignore and fall through
 137                }
 138            }
 139            if (FileBackend.getFileSize(context, attachment.getUri()) > max) {
 140                Log.d(Config.LOGTAG, "not all files are under " + max + " bytes. suggesting falling back to jingle");
 141                return false;
 142            }
 143        }
 144        return true;
 145    }
 146
 147    public static String getConversationsDirectory(Context context, final String type) {
 148        if (Config.ONLY_INTERNAL_STORAGE) {
 149            return context.getFilesDir().getAbsolutePath() + "/" + type + "/";
 150        } else {
 151            return getAppMediaDirectory(context) + context.getString(R.string.app_name) + " " + type + "/";
 152        }
 153    }
 154
 155    public static String getAppMediaDirectory(Context context) {
 156        return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + context.getString(R.string.app_name) + "/Media/";
 157    }
 158
 159    public static String getBackupDirectory(Context context) {
 160        return getBackupDirectory(context.getString(R.string.app_name));
 161    }
 162
 163    public static String getBackupDirectory(String app) {
 164        return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + app + "/Backup/";
 165    }
 166
 167    private static Bitmap rotate(Bitmap bitmap, int degree) {
 168        if (degree == 0) {
 169            return bitmap;
 170        }
 171        int w = bitmap.getWidth();
 172        int h = bitmap.getHeight();
 173        Matrix mtx = new Matrix();
 174        mtx.postRotate(degree);
 175        Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
 176        if (bitmap != null && !bitmap.isRecycled()) {
 177            bitmap.recycle();
 178        }
 179        return result;
 180    }
 181
 182    public static boolean isPathBlacklisted(String path) {
 183        final String androidDataPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/";
 184        return path.startsWith(androidDataPath);
 185    }
 186
 187    private static Paint createAntiAliasingPaint() {
 188        Paint paint = new Paint();
 189        paint.setAntiAlias(true);
 190        paint.setFilterBitmap(true);
 191        paint.setDither(true);
 192        return paint;
 193    }
 194
 195    private static String getTakePhotoPath() {
 196        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
 197    }
 198
 199    public static Uri getUriForUri(Context context, Uri uri) {
 200        if ("file".equals(uri.getScheme())) {
 201            return getUriForFile(context, new File(uri.getPath()));
 202        } else {
 203            return uri;
 204        }
 205    }
 206
 207    public static Uri getUriForFile(Context context, File file) {
 208        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) {
 209            try {
 210                return FileProvider.getUriForFile(context, getAuthority(context), file);
 211            } catch (IllegalArgumentException e) {
 212                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 213                    throw new SecurityException(e);
 214                } else {
 215                    return Uri.fromFile(file);
 216                }
 217            }
 218        } else {
 219            return Uri.fromFile(file);
 220        }
 221    }
 222
 223    public static String getAuthority(Context context) {
 224        return context.getPackageName() + FILE_PROVIDER;
 225    }
 226
 227    private static boolean hasAlpha(final Bitmap bitmap) {
 228        final int w = bitmap.getWidth();
 229        final int h = bitmap.getHeight();
 230        final int yStep = Math.max(1, w / 100);
 231        final int xStep = Math.max(1, h / 100);
 232        for (int x = 0; x < w; x += xStep) {
 233            for (int y = 0; y < h; y += yStep) {
 234                if (Color.alpha(bitmap.getPixel(x, y)) < 255) {
 235                    return true;
 236                }
 237            }
 238        }
 239        return false;
 240    }
 241
 242    private static int calcSampleSize(File image, int size) {
 243        BitmapFactory.Options options = new BitmapFactory.Options();
 244        options.inJustDecodeBounds = true;
 245        BitmapFactory.decodeFile(image.getAbsolutePath(), options);
 246        return calcSampleSize(options, size);
 247    }
 248
 249
 250    private static int calcSampleSize(BitmapFactory.Options options, int size) {
 251        int height = options.outHeight;
 252        int width = options.outWidth;
 253        int inSampleSize = 1;
 254
 255        if (height > size || width > size) {
 256            int halfHeight = height / 2;
 257            int halfWidth = width / 2;
 258
 259            while ((halfHeight / inSampleSize) > size
 260                    && (halfWidth / inSampleSize) > size) {
 261                inSampleSize *= 2;
 262            }
 263        }
 264        return inSampleSize;
 265    }
 266
 267    private static Dimensions getVideoDimensions(Context context, Uri uri) throws NotAVideoFile {
 268        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
 269        try {
 270            mediaMetadataRetriever.setDataSource(context, uri);
 271        } catch (RuntimeException e) {
 272            throw new NotAVideoFile(e);
 273        }
 274        return getVideoDimensions(mediaMetadataRetriever);
 275    }
 276
 277    private static Dimensions getVideoDimensionsOfFrame(MediaMetadataRetriever mediaMetadataRetriever) {
 278        Bitmap bitmap = null;
 279        try {
 280            bitmap = mediaMetadataRetriever.getFrameAtTime();
 281            return new Dimensions(bitmap.getHeight(), bitmap.getWidth());
 282        } catch (Exception e) {
 283            return null;
 284        } finally {
 285            if (bitmap != null) {
 286                bitmap.recycle();
 287            }
 288        }
 289    }
 290
 291    private static Dimensions getVideoDimensions(MediaMetadataRetriever metadataRetriever) throws NotAVideoFile {
 292        String hasVideo = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
 293        if (hasVideo == null) {
 294            throw new NotAVideoFile();
 295        }
 296        Dimensions dimensions = getVideoDimensionsOfFrame(metadataRetriever);
 297        if (dimensions != null) {
 298            return dimensions;
 299        }
 300        final int rotation = extractRotationFromMediaRetriever(metadataRetriever);
 301        boolean rotated = rotation == 90 || rotation == 270;
 302        int height;
 303        try {
 304            String h = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
 305            height = Integer.parseInt(h);
 306        } catch (Exception e) {
 307            height = -1;
 308        }
 309        int width;
 310        try {
 311            String w = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
 312            width = Integer.parseInt(w);
 313        } catch (Exception e) {
 314            width = -1;
 315        }
 316        metadataRetriever.release();
 317        Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height);
 318        return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
 319    }
 320
 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, String url, long size) {
 421        final StringBuilder body = new StringBuilder();
 422        body.append(url).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(final Uri uri) {
 600        final String path = getOriginalPath(uri);
 601        if (path == null || isPathBlacklisted(path)) {
 602            return false;
 603        }
 604        final 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            final InputStream inputStream = mXmppConnectionService.getContentResolver().openInputStream(uri);
 613            BitmapFactory.decodeStream(inputStream, null, options);
 614            close(inputStream);
 615            if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
 616                return false;
 617            }
 618            return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
 619        } catch (FileNotFoundException e) {
 620            Log.d(Config.LOGTAG, "unable to get image dimensions", e);
 621            return false;
 622        }
 623    }
 624
 625    public String getOriginalPath(Uri uri) {
 626        return FileUtils.getPath(mXmppConnectionService, uri);
 627    }
 628
 629    private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
 630        Log.d(Config.LOGTAG, "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
 631        file.getParentFile().mkdirs();
 632        try {
 633            file.createNewFile();
 634        } catch (IOException e) {
 635            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 636        }
 637        try (final OutputStream os = new FileOutputStream(file);
 638             final InputStream is = mXmppConnectionService.getContentResolver().openInputStream(uri)) {
 639            if (is == null) {
 640                throw new FileCopyException(R.string.error_file_not_found);
 641            }
 642            try {
 643                ByteStreams.copy(is, os);
 644            } catch (IOException e) {
 645                throw new FileWriterException();
 646            }
 647            try {
 648                os.flush();
 649            } catch (IOException e) {
 650                throw new FileWriterException();
 651            }
 652        } catch (final FileNotFoundException e) {
 653            cleanup(file);
 654            throw new FileCopyException(R.string.error_file_not_found);
 655        } catch (final FileWriterException e) {
 656            cleanup(file);
 657            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 658        } catch (final SecurityException e) {
 659            cleanup(file);
 660            throw new FileCopyException(R.string.error_security_exception);
 661        } catch (final IOException e) {
 662            cleanup(file);
 663            throw new FileCopyException(R.string.error_io_exception);
 664        }
 665    }
 666
 667    public void copyFileToPrivateStorage(Message message, Uri uri, String type) throws FileCopyException {
 668        String mime = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
 669        Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
 670        String extension = MimeUtils.guessExtensionFromMimeType(mime);
 671        if (extension == null) {
 672            Log.d(Config.LOGTAG, "extension from mime type was null");
 673            extension = getExtensionFromUri(uri);
 674        }
 675        if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
 676            extension = "oga";
 677        }
 678        message.setRelativeFilePath(message.getUuid() + "." + extension);
 679        copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
 680    }
 681
 682    private String getExtensionFromUri(Uri uri) {
 683        String[] projection = {MediaStore.MediaColumns.DATA};
 684        String filename = null;
 685        Cursor cursor;
 686        try {
 687            cursor = mXmppConnectionService.getContentResolver().query(uri, projection, null, null, null);
 688        } catch (IllegalArgumentException e) {
 689            cursor = null;
 690        }
 691        if (cursor != null) {
 692            try {
 693                if (cursor.moveToFirst()) {
 694                    filename = cursor.getString(0);
 695                }
 696            } catch (Exception e) {
 697                filename = null;
 698            } finally {
 699                cursor.close();
 700            }
 701        }
 702        if (filename == null) {
 703            final List<String> segments = uri.getPathSegments();
 704            if (segments.size() > 0) {
 705                filename = segments.get(segments.size() - 1);
 706            }
 707        }
 708        int pos = filename == null ? -1 : filename.lastIndexOf('.');
 709        return pos > 0 ? filename.substring(pos + 1) : null;
 710    }
 711
 712    private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException, ImageCompressionException {
 713        final File parent = file.getParentFile();
 714        if (parent != null && parent.mkdirs()) {
 715            Log.d(Config.LOGTAG, "created parent directory");
 716        }
 717        InputStream is = null;
 718        OutputStream os = null;
 719        try {
 720            if (!file.exists() && !file.createNewFile()) {
 721                throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 722            }
 723            is = mXmppConnectionService.getContentResolver().openInputStream(image);
 724            if (is == null) {
 725                throw new FileCopyException(R.string.error_not_an_image_file);
 726            }
 727            final Bitmap originalBitmap;
 728            final BitmapFactory.Options options = new BitmapFactory.Options();
 729            final int inSampleSize = (int) Math.pow(2, sampleSize);
 730            Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
 731            options.inSampleSize = inSampleSize;
 732            originalBitmap = BitmapFactory.decodeStream(is, null, options);
 733            is.close();
 734            if (originalBitmap == null) {
 735                throw new ImageCompressionException("Source file was not an image");
 736            }
 737            if (!"image/jpeg".equals(options.outMimeType) && hasAlpha(originalBitmap)) {
 738                originalBitmap.recycle();
 739                throw new ImageCompressionException("Source file had alpha channel");
 740            }
 741            Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
 742            final int rotation = getRotation(image);
 743            scaledBitmap = rotate(scaledBitmap, rotation);
 744            boolean targetSizeReached = false;
 745            int quality = Config.IMAGE_QUALITY;
 746            final int imageMaxSize = mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize);
 747            while (!targetSizeReached) {
 748                os = new FileOutputStream(file);
 749                boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
 750                if (!success) {
 751                    throw new FileCopyException(R.string.error_compressing_image);
 752                }
 753                os.flush();
 754                targetSizeReached = file.length() <= imageMaxSize || quality <= 50;
 755                quality -= 5;
 756            }
 757            scaledBitmap.recycle();
 758        } catch (final FileNotFoundException e) {
 759            cleanup(file);
 760            throw new FileCopyException(R.string.error_file_not_found);
 761        } catch (final IOException e) {
 762            cleanup(file);
 763            throw new FileCopyException(R.string.error_io_exception);
 764        } catch (SecurityException e) {
 765            cleanup(file);
 766            throw new FileCopyException(R.string.error_security_exception_during_image_copy);
 767        } catch (final OutOfMemoryError e) {
 768            ++sampleSize;
 769            if (sampleSize <= 3) {
 770                copyImageToPrivateStorage(file, image, sampleSize);
 771            } else {
 772                throw new FileCopyException(R.string.error_out_of_memory);
 773            }
 774        } finally {
 775            close(os);
 776            close(is);
 777        }
 778    }
 779
 780    private static void cleanup(final File file) {
 781        try {
 782            file.delete();
 783        } catch (Exception e) {
 784
 785        }
 786    }
 787
 788    public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException, ImageCompressionException {
 789        Log.d(Config.LOGTAG, "copy image (" + image.toString() + ") to private storage " + file.getAbsolutePath());
 790        copyImageToPrivateStorage(file, image, 0);
 791    }
 792
 793    public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException, ImageCompressionException {
 794        switch (Config.IMAGE_FORMAT) {
 795            case JPEG:
 796                message.setRelativeFilePath(message.getUuid() + ".jpg");
 797                break;
 798            case PNG:
 799                message.setRelativeFilePath(message.getUuid() + ".png");
 800                break;
 801            case WEBP:
 802                message.setRelativeFilePath(message.getUuid() + ".webp");
 803                break;
 804        }
 805        copyImageToPrivateStorage(getFile(message), image);
 806        updateFileParams(message);
 807    }
 808
 809    public boolean unusualBounds(final Uri image) {
 810        try {
 811            final BitmapFactory.Options options = new BitmapFactory.Options();
 812            options.inJustDecodeBounds = true;
 813            final InputStream inputStream = mXmppConnectionService.getContentResolver().openInputStream(image);
 814            BitmapFactory.decodeStream(inputStream, null, options);
 815            close(inputStream);
 816            float ratio = (float) options.outHeight / options.outWidth;
 817            return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
 818        } catch (final Exception e) {
 819            Log.w(Config.LOGTAG, "unable to detect image bounds", e);
 820            return false;
 821        }
 822    }
 823
 824    private int getRotation(final File file) {
 825        try (final InputStream inputStream = new FileInputStream(file)) {
 826            return getRotation(inputStream);
 827        } catch (Exception e) {
 828            return 0;
 829        }
 830    }
 831
 832    private int getRotation(final Uri image) {
 833        try (final InputStream is = mXmppConnectionService.getContentResolver().openInputStream(image)) {
 834            return is == null ? 0 : getRotation(is);
 835        } catch (final Exception e) {
 836            return 0;
 837        }
 838    }
 839
 840    private static int getRotation(final InputStream inputStream) throws IOException {
 841        final ExifInterface exif = new ExifInterface(inputStream);
 842        final int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
 843        switch (orientation) {
 844            case ExifInterface.ORIENTATION_ROTATE_180:
 845                return 180;
 846            case ExifInterface.ORIENTATION_ROTATE_90:
 847                return 90;
 848            case ExifInterface.ORIENTATION_ROTATE_270:
 849                return 270;
 850            default:
 851                return 0;
 852        }
 853    }
 854
 855    public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
 856        final String uuid = message.getUuid();
 857        final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
 858        Bitmap thumbnail = cache.get(uuid);
 859        if ((thumbnail == null) && (!cacheOnly)) {
 860            synchronized (THUMBNAIL_LOCK) {
 861                thumbnail = cache.get(uuid);
 862                if (thumbnail != null) {
 863                    return thumbnail;
 864                }
 865                DownloadableFile file = getFile(message);
 866                final String mime = file.getMimeType();
 867                if ("application/pdf".equals(mime) && Compatibility.runsTwentyOne()) {
 868                    thumbnail = getPdfDocumentPreview(file, size);
 869                } else if (mime.startsWith("video/")) {
 870                    thumbnail = getVideoPreview(file, size);
 871                } else {
 872                    final Bitmap fullSize = getFullSizeImagePreview(file, size);
 873                    if (fullSize == null) {
 874                        throw new FileNotFoundException();
 875                    }
 876                    thumbnail = resize(fullSize, size);
 877                    thumbnail = rotate(thumbnail, getRotation(file));
 878                    if (mime.equals("image/gif")) {
 879                        Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
 880                        drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
 881                        thumbnail.recycle();
 882                        thumbnail = withGifOverlay;
 883                    }
 884                }
 885                cache.put(uuid, thumbnail);
 886            }
 887        }
 888        return thumbnail;
 889    }
 890
 891    private Bitmap getFullSizeImagePreview(File file, int size) {
 892        BitmapFactory.Options options = new BitmapFactory.Options();
 893        options.inSampleSize = calcSampleSize(file, size);
 894        try {
 895            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 896        } catch (OutOfMemoryError e) {
 897            options.inSampleSize *= 2;
 898            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 899        }
 900    }
 901
 902    private void drawOverlay(Bitmap bitmap, int resource, float factor) {
 903        Bitmap overlay = BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
 904        Canvas canvas = new Canvas(bitmap);
 905        float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
 906        Log.d(Config.LOGTAG, "target size overlay: " + targetSize + " overlay bitmap size was " + overlay.getHeight());
 907        float left = (canvas.getWidth() - targetSize) / 2.0f;
 908        float top = (canvas.getHeight() - targetSize) / 2.0f;
 909        RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
 910        canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
 911    }
 912
 913    /**
 914     * https://stackoverflow.com/a/3943023/210897
 915     */
 916    private boolean paintOverlayBlack(final Bitmap bitmap) {
 917        final int h = bitmap.getHeight();
 918        final int w = bitmap.getWidth();
 919        int record = 0;
 920        for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
 921            for (int x = Math.round(w * IGNORE_PADDING); x < w - Math.round(w * IGNORE_PADDING); ++x) {
 922                int pixel = bitmap.getPixel(x, y);
 923                if ((Color.red(pixel) * 0.299 + Color.green(pixel) * 0.587 + Color.blue(pixel) * 0.114) > 186) {
 924                    --record;
 925                } else {
 926                    ++record;
 927                }
 928            }
 929        }
 930        return record < 0;
 931    }
 932
 933    private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
 934        final int h = bitmap.getHeight();
 935        final int w = bitmap.getWidth();
 936        int white = 0;
 937        for (int y = 0; y < h; ++y) {
 938            for (int x = 0; x < w; ++x) {
 939                int pixel = bitmap.getPixel(x, y);
 940                if ((Color.red(pixel) * 0.299 + Color.green(pixel) * 0.587 + Color.blue(pixel) * 0.114) > 186) {
 941                    white++;
 942                }
 943            }
 944        }
 945        return white > (h * w * 0.4f);
 946    }
 947
 948    private Bitmap cropCenterSquareVideo(Uri uri, int size) {
 949        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
 950        Bitmap frame;
 951        try {
 952            metadataRetriever.setDataSource(mXmppConnectionService, uri);
 953            frame = metadataRetriever.getFrameAtTime(0);
 954            metadataRetriever.release();
 955            return cropCenterSquare(frame, size);
 956        } catch (Exception e) {
 957            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
 958            frame.eraseColor(0xff000000);
 959            return frame;
 960        }
 961    }
 962
 963    private Bitmap getVideoPreview(final File file, final int size) {
 964        final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
 965        Bitmap frame;
 966        try {
 967            metadataRetriever.setDataSource(file.getAbsolutePath());
 968            frame = metadataRetriever.getFrameAtTime(0);
 969            metadataRetriever.release();
 970            frame = resize(frame, size);
 971        } catch (IOException | RuntimeException e) {
 972            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
 973            frame.eraseColor(0xff000000);
 974        }
 975        drawOverlay(frame, paintOverlayBlack(frame) ? R.drawable.play_video_black : R.drawable.play_video_white, 0.75f);
 976        return frame;
 977    }
 978
 979    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
 980    private Bitmap getPdfDocumentPreview(final File file, final int size) {
 981        try {
 982            final ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
 983            final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
 984            drawOverlay(rendered, paintOverlayBlackPdf(rendered) ? R.drawable.open_pdf_black : R.drawable.open_pdf_white, 0.75f);
 985            return rendered;
 986        } catch (final IOException | SecurityException e) {
 987            Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
 988            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
 989            placeholder.eraseColor(0xff000000);
 990            return placeholder;
 991        }
 992    }
 993
 994
 995    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
 996    private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
 997        try {
 998            ParcelFileDescriptor fileDescriptor = mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
 999            final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1000            return cropCenterSquare(bitmap, size);
1001        } catch (Exception e) {
1002            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1003            placeholder.eraseColor(0xff000000);
1004            return placeholder;
1005        }
1006    }
1007
1008    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1009    private Bitmap renderPdfDocument(ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1010        final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1011        final PdfRenderer.Page page = pdfRenderer.openPage(0);
1012        final Dimensions dimensions = scalePdfDimensions(new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1013        final Bitmap rendered = Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1014        rendered.eraseColor(0xffffffff);
1015        page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1016        page.close();
1017        pdfRenderer.close();
1018        fileDescriptor.close();
1019        return rendered;
1020    }
1021
1022    public Uri getTakePhotoUri() {
1023        File file;
1024        if (Config.ONLY_INTERNAL_STORAGE) {
1025            file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath(), "Camera/IMG_" + IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
1026        } else {
1027            file = new File(getTakePhotoPath() + "IMG_" + IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
1028        }
1029        file.getParentFile().mkdirs();
1030        return getUriForFile(mXmppConnectionService, file);
1031    }
1032
1033    public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
1034
1035        final Avatar uncompressAvatar = getUncompressedAvatar(image);
1036        if (uncompressAvatar != null && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
1037            return uncompressAvatar;
1038        }
1039        if (uncompressAvatar != null) {
1040            Log.d(Config.LOGTAG, "uncompressed avatar exceeded char limit by " + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
1041        }
1042
1043        Bitmap bm = cropCenterSquare(image, size);
1044        if (bm == null) {
1045            return null;
1046        }
1047        if (hasAlpha(bm)) {
1048            Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
1049            bm.recycle();
1050            bm = cropCenterSquare(image, 96);
1051            return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
1052        }
1053        return getPepAvatar(bm, format, 100);
1054    }
1055
1056    private Avatar getUncompressedAvatar(Uri uri) {
1057        Bitmap bitmap = null;
1058        try {
1059            bitmap = BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri));
1060            return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
1061        } catch (Exception e) {
1062            return null;
1063        } finally {
1064            if (bitmap != null) {
1065                bitmap.recycle();
1066            }
1067        }
1068    }
1069
1070    private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1071        try {
1072            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1073            Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1074            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1075            DigestOutputStream mDigestOutputStream = new DigestOutputStream(mBase64OutputStream, digest);
1076            if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1077                return null;
1078            }
1079            mDigestOutputStream.flush();
1080            mDigestOutputStream.close();
1081            long chars = mByteArrayOutputStream.size();
1082            if (format != Bitmap.CompressFormat.PNG && quality >= 50 && chars >= Config.AVATAR_CHAR_LIMIT) {
1083                int q = quality - 2;
1084                Log.d(Config.LOGTAG, "avatar char length was " + chars + " reducing quality to " + q);
1085                return getPepAvatar(bitmap, format, q);
1086            }
1087            Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1088            final Avatar avatar = new Avatar();
1089            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1090            avatar.image = new String(mByteArrayOutputStream.toByteArray());
1091            if (format.equals(Bitmap.CompressFormat.WEBP)) {
1092                avatar.type = "image/webp";
1093            } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1094                avatar.type = "image/jpeg";
1095            } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1096                avatar.type = "image/png";
1097            }
1098            avatar.width = bitmap.getWidth();
1099            avatar.height = bitmap.getHeight();
1100            return avatar;
1101        } catch (OutOfMemoryError e) {
1102            Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1103            return null;
1104        } catch (Exception e) {
1105            return null;
1106        }
1107    }
1108
1109    public Avatar getStoredPepAvatar(String hash) {
1110        if (hash == null) {
1111            return null;
1112        }
1113        Avatar avatar = new Avatar();
1114        final File file = getAvatarFile(hash);
1115        FileInputStream is = null;
1116        try {
1117            avatar.size = file.length();
1118            BitmapFactory.Options options = new BitmapFactory.Options();
1119            options.inJustDecodeBounds = true;
1120            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1121            is = new FileInputStream(file);
1122            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1123            Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1124            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1125            DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1126            byte[] buffer = new byte[4096];
1127            int length;
1128            while ((length = is.read(buffer)) > 0) {
1129                os.write(buffer, 0, length);
1130            }
1131            os.flush();
1132            os.close();
1133            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1134            avatar.image = new String(mByteArrayOutputStream.toByteArray());
1135            avatar.height = options.outHeight;
1136            avatar.width = options.outWidth;
1137            avatar.type = options.outMimeType;
1138            return avatar;
1139        } catch (NoSuchAlgorithmException | IOException e) {
1140            return null;
1141        } finally {
1142            close(is);
1143        }
1144    }
1145
1146    public boolean isAvatarCached(Avatar avatar) {
1147        final File file = getAvatarFile(avatar.getFilename());
1148        return file.exists();
1149    }
1150
1151    public boolean save(final Avatar avatar) {
1152        File file;
1153        if (isAvatarCached(avatar)) {
1154            file = getAvatarFile(avatar.getFilename());
1155            avatar.size = file.length();
1156        } else {
1157            file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString());
1158            if (file.getParentFile().mkdirs()) {
1159                Log.d(Config.LOGTAG, "created cache directory");
1160            }
1161            OutputStream os = null;
1162            try {
1163                if (!file.createNewFile()) {
1164                    Log.d(Config.LOGTAG, "unable to create temporary file " + file.getAbsolutePath());
1165                }
1166                os = new FileOutputStream(file);
1167                MessageDigest digest = MessageDigest.getInstance("SHA-1");
1168                digest.reset();
1169                DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1170                final byte[] bytes = avatar.getImageAsBytes();
1171                mDigestOutputStream.write(bytes);
1172                mDigestOutputStream.flush();
1173                mDigestOutputStream.close();
1174                String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1175                if (sha1sum.equals(avatar.sha1sum)) {
1176                    final File outputFile = getAvatarFile(avatar.getFilename());
1177                    if (outputFile.getParentFile().mkdirs()) {
1178                        Log.d(Config.LOGTAG, "created avatar directory");
1179                    }
1180                    final File avatarFile = getAvatarFile(avatar.getFilename());
1181                    if (!file.renameTo(avatarFile)) {
1182                        Log.d(Config.LOGTAG, "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1183                        return false;
1184                    }
1185                } else {
1186                    Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1187                    if (!file.delete()) {
1188                        Log.d(Config.LOGTAG, "unable to delete temporary file");
1189                    }
1190                    return false;
1191                }
1192                avatar.size = bytes.length;
1193            } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1194                return false;
1195            } finally {
1196                close(os);
1197            }
1198        }
1199        return true;
1200    }
1201
1202    public void deleteHistoricAvatarPath() {
1203        delete(getHistoricAvatarPath());
1204    }
1205
1206    private void delete(final File file) {
1207        if (file.isDirectory()) {
1208            final File[] files = file.listFiles();
1209            if (files != null) {
1210                for (final File f : files) {
1211                    delete(f);
1212                }
1213            }
1214        }
1215        if (file.delete()) {
1216            Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1217        }
1218    }
1219
1220    private File getHistoricAvatarPath() {
1221        return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1222    }
1223
1224    private File getAvatarFile(String avatar) {
1225        return new File(mXmppConnectionService.getCacheDir(), "/avatars/" + avatar);
1226    }
1227
1228    public Uri getAvatarUri(String avatar) {
1229        return Uri.fromFile(getAvatarFile(avatar));
1230    }
1231
1232    public Bitmap cropCenterSquare(Uri image, int size) {
1233        if (image == null) {
1234            return null;
1235        }
1236        InputStream is = null;
1237        try {
1238            BitmapFactory.Options options = new BitmapFactory.Options();
1239            options.inSampleSize = calcSampleSize(image, size);
1240            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1241            if (is == null) {
1242                return null;
1243            }
1244            Bitmap input = BitmapFactory.decodeStream(is, null, options);
1245            if (input == null) {
1246                return null;
1247            } else {
1248                input = rotate(input, getRotation(image));
1249                return cropCenterSquare(input, size);
1250            }
1251        } catch (FileNotFoundException | SecurityException e) {
1252            Log.d(Config.LOGTAG, "unable to open file " + image.toString(), e);
1253            return null;
1254        } finally {
1255            close(is);
1256        }
1257    }
1258
1259    public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1260        if (image == null) {
1261            return null;
1262        }
1263        InputStream is = null;
1264        try {
1265            BitmapFactory.Options options = new BitmapFactory.Options();
1266            options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1267            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1268            if (is == null) {
1269                return null;
1270            }
1271            Bitmap source = BitmapFactory.decodeStream(is, null, options);
1272            if (source == null) {
1273                return null;
1274            }
1275            int sourceWidth = source.getWidth();
1276            int sourceHeight = source.getHeight();
1277            float xScale = (float) newWidth / sourceWidth;
1278            float yScale = (float) newHeight / sourceHeight;
1279            float scale = Math.max(xScale, yScale);
1280            float scaledWidth = scale * sourceWidth;
1281            float scaledHeight = scale * sourceHeight;
1282            float left = (newWidth - scaledWidth) / 2;
1283            float top = (newHeight - scaledHeight) / 2;
1284
1285            RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1286            Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1287            Canvas canvas = new Canvas(dest);
1288            canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1289            if (source.isRecycled()) {
1290                source.recycle();
1291            }
1292            return dest;
1293        } catch (SecurityException e) {
1294            return null; //android 6.0 with revoked permissions for example
1295        } catch (FileNotFoundException e) {
1296            return null;
1297        } finally {
1298            close(is);
1299        }
1300    }
1301
1302    public Bitmap cropCenterSquare(Bitmap input, int size) {
1303        int w = input.getWidth();
1304        int h = input.getHeight();
1305
1306        float scale = Math.max((float) size / h, (float) size / w);
1307
1308        float outWidth = scale * w;
1309        float outHeight = scale * h;
1310        float left = (size - outWidth) / 2;
1311        float top = (size - outHeight) / 2;
1312        RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1313
1314        Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1315        Canvas canvas = new Canvas(output);
1316        canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1317        if (!input.isRecycled()) {
1318            input.recycle();
1319        }
1320        return output;
1321    }
1322
1323    private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
1324        final BitmapFactory.Options options = new BitmapFactory.Options();
1325        options.inJustDecodeBounds = true;
1326        final InputStream inputStream = mXmppConnectionService.getContentResolver().openInputStream(image);
1327        BitmapFactory.decodeStream(inputStream, null, options);
1328        close(inputStream);
1329        return calcSampleSize(options, size);
1330    }
1331
1332    public void updateFileParams(Message message) {
1333        updateFileParams(message, null);
1334    }
1335
1336    public void updateFileParams(Message message, String url) {
1337        DownloadableFile file = getFile(message);
1338        final String mime = file.getMimeType();
1339        final boolean privateMessage = message.isPrivateMessage();
1340        final boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
1341        final boolean video = mime != null && mime.startsWith("video/");
1342        final boolean audio = mime != null && mime.startsWith("audio/");
1343        final boolean pdf = "application/pdf".equals(mime);
1344        final StringBuilder body = new StringBuilder();
1345        if (url != null) {
1346            body.append(url);
1347        }
1348        body.append('|').append(file.getSize());
1349        if (image || video || (pdf && Compatibility.runsTwentyOne())) {
1350            try {
1351                final Dimensions dimensions;
1352                if (video) {
1353                    dimensions = getVideoDimensions(file);
1354                } else if (pdf && Compatibility.runsTwentyOne()) {
1355                    dimensions = getPdfDocumentDimensions(file);
1356                } else {
1357                    dimensions = getImageDimensions(file);
1358                }
1359                if (dimensions.valid()) {
1360                    body.append('|').append(dimensions.width).append('|').append(dimensions.height);
1361                }
1362            } catch (NotAVideoFile notAVideoFile) {
1363                Log.d(Config.LOGTAG, "file with mime type " + file.getMimeType() + " was not a video file");
1364                //fall threw
1365            }
1366        } else if (audio) {
1367            body.append("|0|0|").append(getMediaRuntime(file));
1368        }
1369        message.setBody(body.toString());
1370        message.setDeleted(false);
1371        message.setType(privateMessage ? Message.TYPE_PRIVATE_FILE : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
1372    }
1373
1374    private int getMediaRuntime(File file) {
1375        try {
1376            MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1377            mediaMetadataRetriever.setDataSource(file.toString());
1378            return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1379        } catch (RuntimeException e) {
1380            return 0;
1381        }
1382    }
1383
1384    private Dimensions getImageDimensions(File file) {
1385        BitmapFactory.Options options = new BitmapFactory.Options();
1386        options.inJustDecodeBounds = true;
1387        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1388        int rotation = getRotation(file);
1389        boolean rotated = rotation == 90 || rotation == 270;
1390        int imageHeight = rotated ? options.outWidth : options.outHeight;
1391        int imageWidth = rotated ? options.outHeight : options.outWidth;
1392        return new Dimensions(imageHeight, imageWidth);
1393    }
1394
1395    private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1396        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1397        try {
1398            metadataRetriever.setDataSource(file.getAbsolutePath());
1399        } catch (RuntimeException e) {
1400            throw new NotAVideoFile(e);
1401        }
1402        return getVideoDimensions(metadataRetriever);
1403    }
1404
1405    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1406    private Dimensions getPdfDocumentDimensions(final File file) {
1407        final ParcelFileDescriptor fileDescriptor;
1408        try {
1409            fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1410            if (fileDescriptor == null) {
1411                return new Dimensions(0, 0);
1412            }
1413        } catch (FileNotFoundException e) {
1414            return new Dimensions(0, 0);
1415        }
1416        try {
1417            final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1418            final PdfRenderer.Page page = pdfRenderer.openPage(0);
1419            final int height = page.getHeight();
1420            final int width = page.getWidth();
1421            page.close();
1422            pdfRenderer.close();
1423            return scalePdfDimensions(new Dimensions(height, width));
1424        } catch (IOException | SecurityException e) {
1425            Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
1426            return new Dimensions(0, 0);
1427        }
1428    }
1429
1430    private Dimensions scalePdfDimensions(Dimensions in) {
1431        final DisplayMetrics displayMetrics = mXmppConnectionService.getResources().getDisplayMetrics();
1432        final int target = (int) (displayMetrics.density * 288);
1433        return scalePdfDimensions(in, target, true);
1434    }
1435
1436    private static Dimensions scalePdfDimensions(final Dimensions in, final int target, final boolean fit) {
1437        final int w, h;
1438        if (fit == (in.width <= in.height)) {
1439            w = Math.max((int) (in.width / ((double) in.height / target)), 1);
1440            h = target;
1441        } else {
1442            w = target;
1443            h = Math.max((int) (in.height / ((double) in.width / target)), 1);
1444        }
1445        return new Dimensions(h, w);
1446    }
1447
1448    public Bitmap getAvatar(String avatar, int size) {
1449        if (avatar == null) {
1450            return null;
1451        }
1452        Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1453        return bm;
1454    }
1455
1456    private static class Dimensions {
1457        public final int width;
1458        public final int height;
1459
1460        Dimensions(int height, int width) {
1461            this.width = width;
1462            this.height = height;
1463        }
1464
1465        public int getMin() {
1466            return Math.min(width, height);
1467        }
1468
1469        public boolean valid() {
1470            return width > 0 && height > 0;
1471        }
1472    }
1473
1474    private static class NotAVideoFile extends Exception {
1475        public NotAVideoFile(Throwable t) {
1476            super(t);
1477        }
1478
1479        public NotAVideoFile() {
1480            super();
1481        }
1482    }
1483
1484    public static class ImageCompressionException extends Exception {
1485
1486        ImageCompressionException(String message) {
1487            super(message);
1488        }
1489    }
1490
1491
1492    public static class FileCopyException extends Exception {
1493        private final int resId;
1494
1495        private FileCopyException(@StringRes int resId) {
1496            this.resId = resId;
1497        }
1498
1499        public @StringRes
1500        int getResId() {
1501            return resId;
1502        }
1503    }
1504}