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