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