FileBackend.java

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