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 boolean paintOverlayBlackPdf(final Bitmap bitmap) {
 890        final int h = bitmap.getHeight();
 891        final int w = bitmap.getWidth();
 892        int white = 0;
 893        for (int y = 0; y < h; ++y) {
 894            for (int x = 0; x < w; ++x) {
 895                int pixel = bitmap.getPixel(x, y);
 896                if ((Color.red(pixel) * 0.299 + Color.green(pixel) * 0.587 + Color.blue(pixel) * 0.114) > 186) {
 897                    white++;
 898                }
 899            }
 900        }
 901        return white > (h * w * 0.4f);
 902    }
 903
 904    private Bitmap cropCenterSquareVideo(Uri uri, int size) {
 905        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
 906        Bitmap frame;
 907        try {
 908            metadataRetriever.setDataSource(mXmppConnectionService, uri);
 909            frame = metadataRetriever.getFrameAtTime(0);
 910            metadataRetriever.release();
 911            return cropCenterSquare(frame, size);
 912        } catch (Exception e) {
 913            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
 914            frame.eraseColor(0xff000000);
 915            return frame;
 916        }
 917    }
 918
 919    private Bitmap getVideoPreview(final File file, final int size) {
 920        final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
 921        Bitmap frame;
 922        try {
 923            metadataRetriever.setDataSource(file.getAbsolutePath());
 924            frame = metadataRetriever.getFrameAtTime(0);
 925            metadataRetriever.release();
 926            frame = resize(frame, size);
 927        } catch (IOException | RuntimeException e) {
 928            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
 929            frame.eraseColor(0xff000000);
 930        }
 931        drawOverlay(frame, paintOverlayBlack(frame) ? R.drawable.play_video_black : R.drawable.play_video_white, 0.75f);
 932        return frame;
 933    }
 934
 935    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
 936    private Bitmap getPdfDocumentPreview(final File file, final int size) {
 937        try {
 938            final ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
 939            final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
 940            final PdfRenderer.Page page = pdfRenderer.openPage(0);
 941            Dimensions dimensions = scalePdfDimensions(new Dimensions(page.getHeight(), page.getWidth()));
 942            final Bitmap rendered = Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
 943            rendered.eraseColor(0xffffffff);
 944            page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
 945            drawOverlay(rendered, paintOverlayBlackPdf(rendered) ? R.drawable.open_pdf_black : R.drawable.open_pdf_white, 0.75f);
 946            return rendered;
 947        } catch (IOException e) {
 948            Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
 949            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
 950            placeholder.eraseColor(0xff000000);
 951            return placeholder;
 952        }
 953    }
 954
 955    public Uri getTakePhotoUri() {
 956        File file;
 957        if (Config.ONLY_INTERNAL_STORAGE) {
 958            file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath(), "Camera/IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
 959        } else {
 960            file = new File(getTakePhotoPath() + "IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
 961        }
 962        file.getParentFile().mkdirs();
 963        return getUriForFile(mXmppConnectionService, file);
 964    }
 965
 966    public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
 967
 968        final Avatar uncompressAvatar = getUncompressedAvatar(image);
 969        if (uncompressAvatar != null && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
 970            return uncompressAvatar;
 971        }
 972        if (uncompressAvatar != null) {
 973            Log.d(Config.LOGTAG, "uncompressed avatar exceeded char limit by " + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
 974        }
 975
 976        Bitmap bm = cropCenterSquare(image, size);
 977        if (bm == null) {
 978            return null;
 979        }
 980        if (hasAlpha(bm)) {
 981            Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
 982            bm.recycle();
 983            bm = cropCenterSquare(image, 96);
 984            return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
 985        }
 986        return getPepAvatar(bm, format, 100);
 987    }
 988
 989    private Avatar getUncompressedAvatar(Uri uri) {
 990        Bitmap bitmap = null;
 991        try {
 992            bitmap = BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri));
 993            return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
 994        } catch (Exception e) {
 995            return null;
 996        } finally {
 997            if (bitmap != null) {
 998                bitmap.recycle();
 999            }
1000        }
1001    }
1002
1003    private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1004        try {
1005            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1006            Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1007            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1008            DigestOutputStream mDigestOutputStream = new DigestOutputStream(mBase64OutputStream, digest);
1009            if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1010                return null;
1011            }
1012            mDigestOutputStream.flush();
1013            mDigestOutputStream.close();
1014            long chars = mByteArrayOutputStream.size();
1015            if (format != Bitmap.CompressFormat.PNG && quality >= 50 && chars >= Config.AVATAR_CHAR_LIMIT) {
1016                int q = quality - 2;
1017                Log.d(Config.LOGTAG, "avatar char length was " + chars + " reducing quality to " + q);
1018                return getPepAvatar(bitmap, format, q);
1019            }
1020            Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1021            final Avatar avatar = new Avatar();
1022            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1023            avatar.image = new String(mByteArrayOutputStream.toByteArray());
1024            if (format.equals(Bitmap.CompressFormat.WEBP)) {
1025                avatar.type = "image/webp";
1026            } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1027                avatar.type = "image/jpeg";
1028            } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1029                avatar.type = "image/png";
1030            }
1031            avatar.width = bitmap.getWidth();
1032            avatar.height = bitmap.getHeight();
1033            return avatar;
1034        } catch (OutOfMemoryError e) {
1035            Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1036            return null;
1037        } catch (Exception e) {
1038            return null;
1039        }
1040    }
1041
1042    public Avatar getStoredPepAvatar(String hash) {
1043        if (hash == null) {
1044            return null;
1045        }
1046        Avatar avatar = new Avatar();
1047        File file = new File(getAvatarPath(hash));
1048        FileInputStream is = null;
1049        try {
1050            avatar.size = file.length();
1051            BitmapFactory.Options options = new BitmapFactory.Options();
1052            options.inJustDecodeBounds = true;
1053            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1054            is = new FileInputStream(file);
1055            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1056            Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1057            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1058            DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1059            byte[] buffer = new byte[4096];
1060            int length;
1061            while ((length = is.read(buffer)) > 0) {
1062                os.write(buffer, 0, length);
1063            }
1064            os.flush();
1065            os.close();
1066            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1067            avatar.image = new String(mByteArrayOutputStream.toByteArray());
1068            avatar.height = options.outHeight;
1069            avatar.width = options.outWidth;
1070            avatar.type = options.outMimeType;
1071            return avatar;
1072        } catch (NoSuchAlgorithmException | IOException e) {
1073            return null;
1074        } finally {
1075            close(is);
1076        }
1077    }
1078
1079    public boolean isAvatarCached(Avatar avatar) {
1080        File file = new File(getAvatarPath(avatar.getFilename()));
1081        return file.exists();
1082    }
1083
1084    public boolean save(final Avatar avatar) {
1085        File file;
1086        if (isAvatarCached(avatar)) {
1087            file = new File(getAvatarPath(avatar.getFilename()));
1088            avatar.size = file.length();
1089        } else {
1090            file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString());
1091            if (file.getParentFile().mkdirs()) {
1092                Log.d(Config.LOGTAG, "created cache directory");
1093            }
1094            OutputStream os = null;
1095            try {
1096                if (!file.createNewFile()) {
1097                    Log.d(Config.LOGTAG, "unable to create temporary file " + file.getAbsolutePath());
1098                }
1099                os = new FileOutputStream(file);
1100                MessageDigest digest = MessageDigest.getInstance("SHA-1");
1101                digest.reset();
1102                DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1103                final byte[] bytes = avatar.getImageAsBytes();
1104                mDigestOutputStream.write(bytes);
1105                mDigestOutputStream.flush();
1106                mDigestOutputStream.close();
1107                String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1108                if (sha1sum.equals(avatar.sha1sum)) {
1109                    File outputFile = new File(getAvatarPath(avatar.getFilename()));
1110                    if (outputFile.getParentFile().mkdirs()) {
1111                        Log.d(Config.LOGTAG, "created avatar directory");
1112                    }
1113                    String filename = getAvatarPath(avatar.getFilename());
1114                    if (!file.renameTo(new File(filename))) {
1115                        Log.d(Config.LOGTAG, "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1116                        return false;
1117                    }
1118                } else {
1119                    Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1120                    if (!file.delete()) {
1121                        Log.d(Config.LOGTAG, "unable to delete temporary file");
1122                    }
1123                    return false;
1124                }
1125                avatar.size = bytes.length;
1126            } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1127                return false;
1128            } finally {
1129                close(os);
1130            }
1131        }
1132        return true;
1133    }
1134
1135    private String getAvatarPath(String avatar) {
1136        return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/avatars/" + avatar;
1137    }
1138
1139    public Uri getAvatarUri(String avatar) {
1140        return Uri.parse("file:" + getAvatarPath(avatar));
1141    }
1142
1143    public Bitmap cropCenterSquare(Uri image, int size) {
1144        if (image == null) {
1145            return null;
1146        }
1147        InputStream is = null;
1148        try {
1149            BitmapFactory.Options options = new BitmapFactory.Options();
1150            options.inSampleSize = calcSampleSize(image, size);
1151            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1152            if (is == null) {
1153                return null;
1154            }
1155            Bitmap input = BitmapFactory.decodeStream(is, null, options);
1156            if (input == null) {
1157                return null;
1158            } else {
1159                input = rotate(input, getRotation(image));
1160                return cropCenterSquare(input, size);
1161            }
1162        } catch (FileNotFoundException | SecurityException e) {
1163            Log.d(Config.LOGTAG, "unable to open file " + image.toString(), e);
1164            return null;
1165        } finally {
1166            close(is);
1167        }
1168    }
1169
1170    public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1171        if (image == null) {
1172            return null;
1173        }
1174        InputStream is = null;
1175        try {
1176            BitmapFactory.Options options = new BitmapFactory.Options();
1177            options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1178            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1179            if (is == null) {
1180                return null;
1181            }
1182            Bitmap source = BitmapFactory.decodeStream(is, null, options);
1183            if (source == null) {
1184                return null;
1185            }
1186            int sourceWidth = source.getWidth();
1187            int sourceHeight = source.getHeight();
1188            float xScale = (float) newWidth / sourceWidth;
1189            float yScale = (float) newHeight / sourceHeight;
1190            float scale = Math.max(xScale, yScale);
1191            float scaledWidth = scale * sourceWidth;
1192            float scaledHeight = scale * sourceHeight;
1193            float left = (newWidth - scaledWidth) / 2;
1194            float top = (newHeight - scaledHeight) / 2;
1195
1196            RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1197            Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1198            Canvas canvas = new Canvas(dest);
1199            canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1200            if (source.isRecycled()) {
1201                source.recycle();
1202            }
1203            return dest;
1204        } catch (SecurityException e) {
1205            return null; //android 6.0 with revoked permissions for example
1206        } catch (FileNotFoundException e) {
1207            return null;
1208        } finally {
1209            close(is);
1210        }
1211    }
1212
1213    public Bitmap cropCenterSquare(Bitmap input, int size) {
1214        int w = input.getWidth();
1215        int h = input.getHeight();
1216
1217        float scale = Math.max((float) size / h, (float) size / w);
1218
1219        float outWidth = scale * w;
1220        float outHeight = scale * h;
1221        float left = (size - outWidth) / 2;
1222        float top = (size - outHeight) / 2;
1223        RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1224
1225        Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1226        Canvas canvas = new Canvas(output);
1227        canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1228        if (!input.isRecycled()) {
1229            input.recycle();
1230        }
1231        return output;
1232    }
1233
1234    private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
1235        BitmapFactory.Options options = new BitmapFactory.Options();
1236        options.inJustDecodeBounds = true;
1237        BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
1238        return calcSampleSize(options, size);
1239    }
1240
1241    public void updateFileParams(Message message) {
1242        updateFileParams(message, null);
1243    }
1244
1245    public void updateFileParams(Message message, URL url) {
1246        DownloadableFile file = getFile(message);
1247        final String mime = file.getMimeType();
1248        final boolean privateMessage = message.isPrivateMessage();
1249        final boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
1250        final boolean video = mime != null && mime.startsWith("video/");
1251        final boolean audio = mime != null && mime.startsWith("audio/");
1252        final boolean pdf = "application/pdf".equals(mime);
1253        final StringBuilder body = new StringBuilder();
1254        if (url != null) {
1255            body.append(url.toString());
1256        }
1257        body.append('|').append(file.getSize());
1258        if (image || video || (pdf && Compatibility.runsTwentyOne())) {
1259            try {
1260                final Dimensions dimensions;
1261                if (video) {
1262                    dimensions = getVideoDimensions(file);
1263                } else if (pdf && Compatibility.runsTwentyOne()) {
1264                    dimensions = getPdfDocumentDimensions(file);
1265                } else {
1266                    dimensions = getImageDimensions(file);
1267                }
1268                if (dimensions.valid()) {
1269                    body.append('|').append(dimensions.width).append('|').append(dimensions.height);
1270                }
1271            } catch (NotAVideoFile notAVideoFile) {
1272                Log.d(Config.LOGTAG, "file with mime type " + file.getMimeType() + " was not a video file");
1273                //fall threw
1274            }
1275        } else if (audio) {
1276            body.append("|0|0|").append(getMediaRuntime(file));
1277        }
1278        message.setBody(body.toString());
1279        message.setDeleted(false);
1280        message.setType(privateMessage ? Message.TYPE_PRIVATE_FILE : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
1281    }
1282
1283    private int getMediaRuntime(File file) {
1284        try {
1285            MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1286            mediaMetadataRetriever.setDataSource(file.toString());
1287            return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1288        } catch (RuntimeException e) {
1289            return 0;
1290        }
1291    }
1292
1293    private Dimensions getImageDimensions(File file) {
1294        BitmapFactory.Options options = new BitmapFactory.Options();
1295        options.inJustDecodeBounds = true;
1296        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1297        int rotation = getRotation(file);
1298        boolean rotated = rotation == 90 || rotation == 270;
1299        int imageHeight = rotated ? options.outWidth : options.outHeight;
1300        int imageWidth = rotated ? options.outHeight : options.outWidth;
1301        return new Dimensions(imageHeight, imageWidth);
1302    }
1303
1304    private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1305        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1306        try {
1307            metadataRetriever.setDataSource(file.getAbsolutePath());
1308        } catch (RuntimeException e) {
1309            throw new NotAVideoFile(e);
1310        }
1311        return getVideoDimensions(metadataRetriever);
1312    }
1313
1314    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1315    private Dimensions getPdfDocumentDimensions(final File file) {
1316        final ParcelFileDescriptor fileDescriptor;
1317        try {
1318            fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1319            if (fileDescriptor == null) {
1320                return new Dimensions(0, 0);
1321            }
1322        } catch (FileNotFoundException e) {
1323            return new Dimensions(0, 0);
1324        }
1325        try {
1326            final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1327            final PdfRenderer.Page page = pdfRenderer.openPage(0);
1328            final int height = page.getHeight();
1329            final int width = page.getWidth();
1330            page.close();
1331            pdfRenderer.close();
1332            return scalePdfDimensions(new Dimensions(height, width));
1333        } catch (IOException e) {
1334            Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
1335            return new Dimensions(0, 0);
1336        }
1337    }
1338
1339    private Dimensions scalePdfDimensions(Dimensions in) {
1340        final DisplayMetrics displayMetrics = mXmppConnectionService.getResources().getDisplayMetrics();
1341        final int target = (int) (displayMetrics.density * 288);
1342        final int w, h;
1343        if (in.width <= in.height) {
1344            w = Math.max((int) (in.width / ((double) in.height / target)), 1);
1345            h = target;
1346        } else {
1347            w = target;
1348            h = Math.max((int) (in.height / ((double) in.width / target)), 1);
1349        }
1350        return new Dimensions(h, w);
1351    }
1352
1353    public Bitmap getAvatar(String avatar, int size) {
1354        if (avatar == null) {
1355            return null;
1356        }
1357        Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1358        if (bm == null) {
1359            return null;
1360        }
1361        return bm;
1362    }
1363
1364    private static class Dimensions {
1365        public final int width;
1366        public final int height;
1367
1368        Dimensions(int height, int width) {
1369            this.width = width;
1370            this.height = height;
1371        }
1372
1373        public int getMin() {
1374            return Math.min(width, height);
1375        }
1376
1377        public boolean valid() {
1378            return width > 0 && height > 0;
1379        }
1380    }
1381
1382    private static class NotAVideoFile extends Exception {
1383        public NotAVideoFile(Throwable t) {
1384            super(t);
1385        }
1386
1387        public NotAVideoFile() {
1388            super();
1389        }
1390    }
1391
1392    public class FileCopyException extends Exception {
1393        private static final long serialVersionUID = -1010013599132881427L;
1394        private int resId;
1395
1396        public FileCopyException(int resId) {
1397            this.resId = resId;
1398        }
1399
1400        public int getResId() {
1401            return resId;
1402        }
1403    }
1404}