FileBackend.java

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