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