FileBackend.java

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